Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/WP7: Working with a JSON object that includes an array of JSON objects

I'm new to using JSON and JSON.net and I am having trouble with an array of JSON objects within a JSON object. I am using JSON.net as other examples I have seen make it seem straight forward to use.

I am downloading the following JSON string from the internet:

{"count":2,"data":[{"modifydate":12345,"key":"abcdef", "content":"test file 1"},{"modifydate":67891,"key":"ghjikl", "content":"test file 2"}]}

I know that it needs to be deserialised and to do that I need a JSON class that I've written:

    public class NOTE
    {
        [JsonProperty(PropertyName = "count")]
        public int count { get; set; }

        [JsonProperty(PropertyName = "key")]
        public string key { get; set; }

        [JsonProperty(PropertyName = "modifydate")]
        public float modifydate { get; set; }

        [JsonProperty(PropertyName = "content")]
        public string modifydate { get; set; }

    }

So I deserialise it using:

NOTE note = JsonConvert.DeserializeObject<NOTE>(e.Result);

This works fine as I can access the count property and read it fine but everything in the data property I cannot. It seems to me to be an array of JSON objects and its that I'm having trouble with, I would like to be able to get a list of, say, all the "key" values or all the "content" strings.

I've tried lots of methods from here and nothign seems to have worked/I've not been able to find a situation exactly like mine that I can compare against.

If someone could give me a hand that would be fantastic :)

like image 890
Lewis Avatar asked Mar 06 '26 19:03

Lewis


1 Answers

Your JSON has nested objects whereas the object that you're trying to deserialize to has no nested objects. You need the proper hierarchy for things to work properly:

public class Note
{
    [JsonProperty(PropertyName = "count")]
    public int Count { get; set; }

    [JsonProperty(PropertyName = "data")]
    public Data[] Data { get; set; }
}

public class Data
{
    [JsonProperty(PropertyName = "modifydate")]
    public float ModifyDate { get; set; }

    [JsonProperty(PropertyName = "key")]
    public string Key { get; set; }

    [JsonProperty(PropertyName = "content")]
    public string Content { get; set; }
}

Now you should be able to deserialize things properly:

var note = JsonConvert.DeserializeObject<Note>(e.Result);
// loop through the Data elements and show content

foreach(var data in note.Data)
{
    Console.WriteLine(data.content);
}
like image 74
Justin Niessner Avatar answered Mar 09 '26 09:03

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!