-3

I have a requirement to read the json in which keys are vary and store into dictionary in C#.net. I am using Newtonsoft json. I am deserializing like below.

var inputData = JsonConvert.DeserializeObject<dynamic>(myObj)

If the keys are fixed I can do like below.

var val = inputData.Account;

But here keys are dynamic. Below is my json data.

 {
     "data": {
                "Account": "150.80",
                "Name": "XYZ",
                "Description": "Some Value"
             }
 }

Here name value pairs may change. i.e., It may have like below also.

 {
         "data": {
                    "Cost": "154.80",
                    "Type": "S1234",
                    "Period": "Some Value"
                 }
 }

How to access dynamic keys and store into a dictionary.

User
  • 804
  • 8
  • 22
  • Use JSON.Net, it lets you deserialize the information into dynamic dictionaries. – code4life Aug 09 '17 at 15:27
  • 1
    Possible duplicate of [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Adam Aug 09 '17 at 15:29

1 Answers1

1

EDIT: This answer was for the previous posted question, not the newly revised question... I'm leaving it in, since it probably has some useful details.

I'd recommend using Json.NET to do this.

If the fact that the json data always has the field named data, then you can write fairly predictable code to output the contents of data into a dictionary.

Off the top of my head, I'd probably go for an anonymous type-based deserialization, kind of like this:

var json = @"{
 ""data"": {
            ""Account"": ""150.80"",
            ""Name"": ""XYZ"",
            ""Description"": ""Some Value""
           }
 }";

var schema = new { data = new Dictionary<string, object>()};
var result = JsonConvert.DeserializeAnonymousType(json, schema);

You'd have to reach into result.data to get that dictionary.

You could also just use JObject to pull out the values from data directly, but probably would need to parse that data into a dictionary, so it'd be sort of a double call going on, like this:

var jobj = JObject.Parse(json);
var data = jobj["data"];
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>
              (data.ToString());

There's probably more ways to do this even more efficiently. Like I said, these are just ideas off the top of my head.

code4life
  • 15,655
  • 7
  • 50
  • 82
  • Thanks @code4life. Your answer is perfect and suits my requirement. But I do not know why others are not able to understand and down voted my question. I referred my question in the internet, as the answer is not available then I posted my question here – User Aug 09 '17 at 16:17