开发者

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 deser开发者_JAVA技巧ializeobject 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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜