1

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?

3
  • 2
    This JSON doesn't validate. Try it on jsonlint.com Commented Aug 12, 2015 at 7:16
  • my bad, ive fixed it :/ Commented Aug 12, 2015 at 7:21
  • I'm a big fan of json2csharp.com. Commented Aug 12, 2015 at 7:30

2 Answers 2

4

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...");
Sign up to request clarification or add additional context in comments.

2 Comments

oh that is great thanks a lot! i should have got this myself!
You are welcome man. If this is your answer so mark is as answer.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.