Search code examples
c#jsonserializationdeserializationjson-deserialization

Json.NET (Newtonsoft) to parse somewhat dynamic data (c#)


using c# - I have a string of valid json, and am attempting to parse it into a Dictionary but am struggling with the syntax to do so.

Here's an example of the data I'd like to parse:

{
  "data": {
    "KeyOne": {
      "val": "first!"
      "fooBar": "invalid data not needed",
    },
    "anotherKey": {
      "val": null
    },
    "TheThirdKey": {
      "val": 999
      "fooFooBarBar": "more unneeded data",
    },
    "KeyKeyKey": {
      "val": "super neato something"
    },
    ...

this needs to be moved into a Dictionary<string, object> with some fairly specific rules:

  1. the ever changing element name is the key ('KeyOne', 'anotherKey'...) - this is unique within the dataset
  2. for the dictionary value, I ONLY need the string or number or null that is the value of 'val' ('first', null, 999, ...)

so my final dictionary should be something like:

"KeyOne"     : "first!"
"anotherKey" : null
"TheThirdKey": 999
"KeyKeyKey"  : "super neato something"

I've tried to parse this using different variations of

JsonConvert.DeserializeObject<Dictionary<string, object>

I've also tried iterating over the jTokens as such:

JObject jObject = JObject.Parse(jsonString);
List<JToken> jTokens = jObject["data"].Children().ToList();
foreach (JToken jToken in jTokens) { ...

but after so many hours of trying, I am getting embarrassingly nowhere... Hopefully this is something that can be performed with Json.NET, but I have yet to figure it out.

Thoughts?


Solution

  • You could do it this way:

    JObject jObject = JObject.Parse(jsonString);
    var dataChildren = jObject["data"].Children().Cast<JProperty>();
    Dictionary<string, object> result = dataChildren
           .ToDictionary(x => x.Name, x => x.Value["val"].Value<JValue>().Value);
    

    You will get a Dictionary<string,object> as a result