user626528 user626528 - 2 years ago 117
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?

Answer Source

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

var dict= JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download