使用Json.Net在C#中进行Json解析 [英] Json Parsing in c# using Json.Net
问题描述
{"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. &为此,我的代码是:
I am trying to parse this json. & For this I my code is:
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;
}
我已经尝试了以下两种方法:
I have tried both of this following way:
var container = DeserializeFromJson<DataJsonAttributeContainer>(e.Result);
& var container = DeserializeFromJson<List<Attributes>>(e.Result);
Json字符串播种完全正常,但是从json字符串反序列化时程序崩溃. 我想,我在这里犯了一个非常愚蠢的错误&我想不明白.有人可以在这方面帮助我吗? 提前致谢.
Json string sownloads completely fine but program crashes in while deserializing from json string. I guess, I have made a very silly mistake here & I can not figure it out. Can anyone please help me in this regard? Thanks in advance.
推荐答案
在deserializing
时,您只是将Posts
排除在外,如果您要deserialize
Posts
的内部项目,则您必须在Posts
中提及它deserialization
u are simply excluding Posts
when deserializing
, if u want to deserialize
inner items of Posts
, than u have to mention it in 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"]);
这篇关于使用Json.Net在C#中进行Json解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!