user626528 user626528 - 1 month ago 20
C# Question

Map properties to a list of objects

I have a JSON data that looks like this:

{
"Item1": {
"Field1": "Val1",
"Field2": "Val2"
},
"Item2": {
"Field1": "Val11",
"Field2": "Val22"
}
}


I need to deserialize it to a set of classes that look like this:

public class Root
{
public List<Item> Items; // << Item1 and Item2 should go here
}

public class Item
{
public string Field1;
public string Field2;
}


How can I make Newtonsoft.Json to map data this way when deserializing?

L.B L.B
Answer Source

No need for class Root. I would deserialize to a Dictionary

var dict= JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);