Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON to dictionary using LINQ to JSON

Tags:

c#

linq

json.net

I have some JSON like this (serializes from a dictionary):

{
  "Context":
  {
    "Test": "Test"
  }
}

And would like to use JSON.NET's JSON to LINQ to deserialize it into a dictionary.

I've tried something different things:

var obj = JObject.Parse(json);
obj.Value<Dictionary<string, string>>("Context");

But this throws an exception like this:

System.InvalidCastException
Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken

I've have also tried:

var obj = JObject.Parse(json);
var context = obj.Values("Context");

But then I can't figure out how to process the elements into a dictionary.

like image 437
Xharze Avatar asked Mar 03 '13 23:03

Xharze


People also ask

How to query using LINQ to JSON in JSON?

Json.NET’s LINQ to JSON is good for traversing your JSON to get it into the .NET data structure you need. In our case, we can use JObject and JProperty On line 6, we parse the JSON string into a JObject, which allows us to query using LINQ to JSON. We then parse the companies JSON properties into IEnumerable<JProperty>

How to write objects as JSON (serialize)?

How to write.NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer.Serialize method. The following example creates JSON as a string:

How to convert JSON string to dictionary?

But if you want to directly convert the json string to dictionary you can try following code snippet. Dictionary<string, object> values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); Share Improve this answer Follow edited Sep 30 '16 at 8:30 RobPethi 5331010 silver badges2626 bronze badges

How do I deserialize a JSON file in Python?

Use the Utf8JsonReader directly. Copy the JSON that you need to deserialize. Create a class file and delete the template code. Choose Edit > Paste Special > Paste JSON as Classes . The result is a class that you can use for your deserialization target.


1 Answers

This should work for you:

string json = "{\"Context\":{\"Test\": \"Test\"}}";
var obj = JObject.Parse(json);
var dict = obj["Context"].ToObject<Dictionary<string,string>>();
like image 166
JoshVarty Avatar answered Sep 24 '22 15:09

JoshVarty