0

I'm trying to parse a source that already exists, and have been using json2csharp.com to generate the classes.

I'm using Newtonsoft to do it.

Some of my data is being converted into classes, when it is closer to a Dictionary.

For example: {

"items":{ "1061":{ "count":"1", "in_use":"0" }, "1065":{ "count":"1", "in_use":"0" } } }

I'd like to have a Class Item with string count, and string in_use and possibly a dictionary under root such that Dictionary items or just a list of items, and put the ID in the object itself.

If most of my object is parsed properly, how do I manually build this part? Do I iterate through the items by pulling down the object as dynamic, and load it manually? What's the best way to do this?

Thanks for the help!

pcaston2
  • 421
  • 1
  • 6
  • 17
  • You could try [this approach](http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net) and modify it to suit your needs. – ChrisK Dec 09 '13 at 18:42

1 Answers1

2

You can create a class for your Class Item:

public class Item
{
    public string count { get; set; }
    public string in_use { get; set; }
}

And then read the values in a dictionary:

string json = @"{
    ""1061"":{
        ""count"":""1"",
        ""in_use"":""0""
    },
    ""1065"":{
        ""count"":""1"",
        ""in_use"":""0""
    }
}";

Dictionary<string, Item> values = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
fcuesta
  • 4,429
  • 1
  • 18
  • 13
  • That method is sound, but I should elaborate. The JSON above is nested within other JSON objects so I would need to extract this section of JSON to parse it as mentioned. Is there a method for that? I could use RegEx or a stack to parse it from the string... I was hoping for something more elegant though. – pcaston2 Dec 09 '13 at 21:36
  • can you provide the full json? you can probably create a more complex class structure that meet your needs. – fcuesta Dec 09 '13 at 22:34
  • There are multiple JSONs that I am parsing that have similar issues, I'd rather not post them all. I've included the root and the element "items" as they appear in the JSON. There are other elements alongside item but I have excluded them. Should I make items a Dictionary of type ? Will it automatically parse the sub element as an Item and fill it this way? – pcaston2 Dec 10 '13 at 00:36
  • I got it, I put Dictionary items { get; set; } and it loaded properly, thanks so much! I will keep using this method, it's elegant. – pcaston2 Dec 10 '13 at 03:30