简体   繁体   中英

nested json c# object deserialization

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 ?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM