tags:

views:

68

answers:

1

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 ?

+4  A: 

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?

Jon Skeet
Jon Skeet, thanks for the reply.I get the same result as you.The issue is that for me ... the Stream object properties are either null or 0.that is item.References[0].Type == nulland so on ... does that not happen to you ?
lboregard
@Iboregard: Ah, sorry - I'd thought your `List<T>` values were null. Investigating...
Jon Skeet
@Jon Skeet, got it ... works perfectly now !!! thanks a lot !
lboregard