Neil Hosey
Neil Hosey

Reputation: 465

JSON mapping to C# class

I have a piece of JSON like this:

{
"Site 1": [
    {
        "Stuff": [
            "detergent",
            "det1"
        ],
        "productLine": "Hay",
        "revenue": {
            "1": 3123,
            "2": 123123,
            "3": 123123
        }
    },
    {
        "Stuff": [
            "detergent",
            "det2"
        ],
        "productLine": "Machine",
        "revenue": {
            "1": 343123,
            "2": 1231321323,
            "3": 321
        }
    }
],
"Site 2": [
    {
        "Stuff": [
            "detergent",
            "det1"
        ],
        "productLine": "Hay",
        "revenue": {
            "1": 111,
            "2": 123123,
            "3": 3213
        }
    },
    {
        "Stuff": [
            "detergent",
            "det2"
        ],
        "productLine": "Machine",
        "revenue": {
            "1": 11123,
            "2": 3255,
            "3": 6575
        }
    }
]
}

I want to map this to C# class but my problem is the names Site1 and site2 are what I would think should be a class name? Is there a way to represent this as a C# object?

Upvotes: 1

Views: 169

Answers (2)

Arin Ghazarian
Arin Ghazarian

Reputation: 5305

Your root object is actually a Dictionary<string, List<YourClass>> and YourClass will look like this:

public class YourClass
{
    public string[] Stuff { get; set; }
    public string productLine { get; set; }
    public Dictionary<string, int> revenue { get; set; }
}

Now you can deserialize your json like this:

var dic = JsonConvert.DeserializeObject<Dictionary<string, List<YourClass>>>("Your json string goes here...");

Upvotes: 4

Mark Redman
Mark Redman

Reputation: 24515

On your c# classes that map the same object graph as the json you can add attributes to the Class and properties to map the json exactly, eg for lowercase json properties etc.

see: http://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

Upvotes: 0

Related Questions