3

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 :)

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.