{"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 字符串反序列化时程序崩溃。我想,我在这里犯了一个非常愚蠢的错误,我无法弄清楚。谁能在这方面帮助我?提前谢谢。
有一些页面可以帮助您从 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);
请注意,您可以根据需要重命名类,并使用这些名称而不是生成的名称。
你只是在deserializing
时排除Posts
,如果你想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"]);