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.
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.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:
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
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.
This should work for you:
string json = "{\"Context\":{\"Test\": \"Test\"}}";
var obj = JObject.Parse(json);
var dict = obj["Context"].ToObject<Dictionary<string,string>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With