-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"          
    },
......
  }
}
2
  • json2csharp.com might also come in handy. Commented Jul 13, 2017 at 5:47
  • To deserialize that JSON into fixed c# objects, upload your JSON to json2csharp.com, then change products into a Dictionary<string, Product> along the lines of this answer, and deserialize with json.net or maybe javascriptserializer. Commented Jul 14, 2017 at 7:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't want A, B, C, D. I want each little thing in "products". Then what is MyType refers to? How does Deserialize know what I want is those each little thing?
Could you please show me some example code? How can I index "products"?
Please see the edit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.