0

I have an API that gives me a list of similar items as different object instead that as members of an array. Let's see the _items node, which contains the available items on a store:

{
    "_ok":200,

    "_store":
          {
           "location":"Rome",
           "open":true
          },
    "_items":
         {
            "itemA":{ "color":"blue","size":3},
            "itemB":{ "color":"red","size":1},
            "itemC":{ "color":"cyan","size":3},
            "itemD":{ "color":"yellow","size":0},
          }

}

I am using the very nice Newtonsoft JSON.NET to do my deserialization, but I do not know how can I get a list of items. it the list was an array, say:

"_items":{["itemA":{ "color":"blue","size":3},"itemB":...

I guess that it would have been easy using JsonConvert to get a

List<Item> 

where Item was a class with color and size member.

. Too bad I can't change the API. thanks.

1 Answer 1

3

You can use JsonExtensionDataAttribute to store the items, and use a property to convert them to Item instances.

[JsonProperty("_items")]
private ItemsContainer _items;


[JsonObject(MemberSerialization.OptIn)]
class ItemsContainer
{
    [JsonExtensionData]
    private IDictionary<string, JToken> _items;

    public IEnumerable<Item> Items
    {
        get
        {
            return _items.Values.Select(i => i.ToObject<Item>());
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, it works perfectly. I've fixed the JSON in my sample code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.