4
{"Posts":
          [{"id":"1",
            "title":"Bibidh prothom khondo",
            "content":"sjih sdkljjdsf kdjsfjks",
            "author":"","last_update":"23 june 2013",
            "Comments":
                [{"id":"1",
                  "content":"sjih sdkljjdsf kdjsfjks",
                  "author":"","last_update":"23 june 2013"}]},
            {"id":"2",
             "title":"Bibidh prothom khondo",
             "content":"sjih sdkljjdsf kdjsfjks",
             "author":"",
             "last_update":"24 june 2013",
             "Comments":[{"id":"1","content":"sjih sdkljjdsf kdjsfjks","author":"","last_update":"23 june 2013"}]},{"id":"3","title":"Bibidh prothom khondo","content":"sjih sdkljjdsf kdjsfjks","author":"","last_update":"25 june 2013"}]}

我正在尝试解析这个 json。&为此,我的代码是:

public class Attributes
    {
        [JsonProperty("id")]
        public string ID { get; set; }
        [JsonProperty("title")]
        public string TITLE { get; set; }
        [JsonProperty("content")]
        public string CONTENT { get; set; }
        [JsonProperty("author")]
        public string AUTHOR { get; set; }
        [JsonProperty("last_update")]
        public string LAST_UPDATE { get; set; }
        [JsonProperty("Comments")]
        public string[] COMMENTS { get; set; }
    }

    public class DataJsonAttributeContainer
    {
        public List<Attributes> attributes { get; set; }
    }

    public static T DeserializeFromJson<T>(string json)
    {
        T deserializedProduct = JsonConvert.DeserializeObject<T>(json);
        return deserializedProduct;
    }

我已经尝试了以下两种方式:

var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);

&var container = DeserializeFromJson<List<Attributes>>(e.Result);

Json 字符串下载完全正常,但程序在从 json 字符串反序列化时崩溃。我想,我在这里犯了一个非常愚蠢的错误,我想不通。任何人都可以在这方面帮助我吗?提前致谢。

4

2 回答 2

5

有一些页面可以帮助您从 JSON 生成数据模型(尽管它不像 F# 人可以做到的那样花哨......)。在此网站上粘贴 JSON并生成数据模型时,会弹出以下类。

public class Comment
{
    public string id { get; set; }
    public string content { get; set; }
    public string author { get; set; }
    public string last_update { get; set; }
}

public class Post
{
    public string id { get; set; }
    public string title { get; set; }
    public string content { get; set; }
    public string author { get; set; }
    public string last_update { get; set; }
    public List<Comment> Comments { get; set; }
}

public class RootObject
{
    public List<Post> Posts { get; set; }
}

我想你必须调用你的解析器,然后从中获取你的属性:

var container = DeserializeFromJson<RootObject>(e.Result);

请注意,您可以根据需要重命名类并使用这些名称而不是生成的名称。


于 2013-07-23T05:45:43.980 回答
4

你只是简单地排除Postsdeserializing,如果你想deserialize内部项目Posts,而不是你必须在deserialization

试试这个 :

var parsed = JObject.Parse(e.Result);
var container = DeserializeFromJson<List<Attributes>>(parsed["Posts"]);

或者

var parsed = JsonSerializer.DeserializeFromString<Dictionary<string,string>>(e.Result);
var container = DeserializeFromJson<List<Attributes>>(parsed["Posts"]);
于 2013-07-23T05:42:26.397 回答