Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested json c# object deserialization

Tags:

c#

json.net

i have the following json string (jsonString)

[
{
"name":"Fruits",
"references":[
    {"stream":{"type":"reference","size":"original",id":"1"}},
    ],
"arts":[
    {"stream":{"type":"art","size":"original","id":"4"}},
    {"stream":{"type":"art","size":"medium","id":"9"}},
    ]
}
]

and the following C# objects

    class Item
    {
        public string Name { get; set; }
        public List<Stream> References { get; set; }
        public List<Stream> Arts { get; set; }

        public Item()
        {
        }
    }

    class Stream
    {
        public string Type { get; set; }
        public string Size { get; set; }
        public string Id { get; set; }

        public Stream()
        {
        }
    }

and the following code

        Item item = JsonConvert.DeserializeObject<Item>(jsonString);

when I run the code, it creteas the correct number of references and arts, but each stream has null value (type = null, size = null).

is it posible to do this json.net deserializeobject method or should I manually deserialize ?

like image 336
lboregard Avatar asked Jan 22 '23 12:01

lboregard


1 Answers

EDIT: Okay, ignore the previous answer. The problem is that your arrays (references and arts) contain objects which in turn contain the relevant data. Basically you've got one layer of wrapping too many. For example, this JSON works fine:

[
{
"name":"Fruits",
"references":[
    {"Type":"reference","Size":"original","Id":"1"},
    ],
"arts":[
    {"Type":"art","Size":"original","id":"4"},
    {"type":"art","size":"medium","id":"9"},
    ]
}
]

If you can't change the JSON, you may need to introduce a new wrapper type into your object model:

public class StreamWrapper
{
    public Stream Stream { get; set; }
}

Then make your Item class have List<StreamWrapper> variables instead of List<Stream>. Does that help?

like image 104
Jon Skeet Avatar answered Jan 24 '23 02:01

Jon Skeet