{"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"}]}
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 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.
There are pages that help you with generating your data model from JSON (though it's not quite as fancy as the way F# folks can do it..). When pasting your JSON on this website and generating the data model the following classes pop out.
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; }
}
I guess you have to call your parser then as follows and grab your attributes out of it:
var container = DeserializeFromJson<RootObject>(e.Result);
Please note that you can rename the classes as you wish and use those names instead of the generated ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With