-2

I need to parse a JSON file using C# into smaller parts. I would like to know how can I parse the JSON to get each product like below from "product"(since I need to store each smaller json in other places)? What kind of code I need to write?

"76V3SF2FJC3ZR3GH" : {
          "id" : "76V3SF2FJC3ZR3GH",
          "attribute1": "AAAAA",
          "attribute2": "BBBBB",
          "attribute3": "CCCCC"        
        }

Example of JSON is like:

{
  "A" : "XXXXX",
  "B" : "XXXXX",
  "C" : "XXXXXX",
  "D" : "XXXXX",
  "products" : {
    "76V3SF2FJC3ZR3GH" : {
      "id" : "76V3SF2FJC3ZR3GH",
      "attribute1": "AAAAA",
      "attribute2": "BBBBB",
      "attribute3": "CCCCC"        
    },
    "RDXNGJU5DRW4G5ZK" : {
      "id" : "RDXNGJU5DRW4G5ZK",
      "attribute1": "AAAAA",
      "attribute2": "BBBBB",
      "attribute3": "CCCCC"          
    },
......
  }
}
bunny
  • 1,797
  • 8
  • 29
  • 58
  • http://json2csharp.com/ might also come in handy. – Uwe Keim Jul 13 '17 at 05:47
  • To deserialize that JSON into fixed c# objects, upload your JSON to http://json2csharp.com, then change `products` into a `Dictionary` along the lines of [this answer](https://stackoverflow.com/a/38793347/3744182), and deserialize with [tag:json.net] or maybe [tag:javascriptserializer]. – dbc Jul 14 '17 at 07:46

1 Answers1

1

You can install Newtonsoft.Json Nuget package and then write:

JsonConvert.Deserialize<MyType>(myJsonString);

Specifying the type is not mandatory and you can deserialize any json into dynamic object with the same method.

-- Edit --

For this case you can use this:

dynamic result = JsonConvert.Deserialize<dynamic>(myJsonString);

now result.products is an object containing different properties with the names like "76V3SF2FJC3ZR3GH" and you can access it like result.products.76V3SF2FJC3ZR3GH.id

If you want to get the list of properties you should use Reflection.

Emad
  • 3,809
  • 3
  • 32
  • 44