C # json nested deserialization

I have the following json line (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 creates the correct number of links and arts, but each thread has a null value (type = null, size = null).

Is it possible to use this json.net deserializeobject method, or should I manually deserialize?

+4
source share
1 answer

EDIT: Ok, ignore the previous answer. The problem is that your arrays (links and art) contain objects, which, in turn, contain relevant data. Basically, you have too many wraps. 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 cannot change the JSON, you may need to introduce a new shell type in your object model:

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

Then make your Item class << 23> instead of List<Stream> . Does it help?

+9
source

All Articles