Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON string to Dictionary<string,object>

Tags:

json

c#

.net

I have this string:

[{ "processLevel" : "1" , "segments" : [{ "min" : "0", "max" : "600" }] }] 

I'm deserializing the object:

object json = jsonSerializer.DeserializeObject(jsonString); 

The object looks like:

object[0] = Key: "processLevel", Value: "1" object[1] = Key: "segments", Value: ... 

And trying to create a dictionary:

Dictionary<string, object> dic = json as Dictionary<string, object>; 

but dic gets null.

What can be the issue ?

like image 686
ohadinho Avatar asked Dec 22 '13 09:12

ohadinho


2 Answers

See mridula's answer for why you are getting null. 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); 
like image 80
santosh singh Avatar answered Sep 20 '22 15:09

santosh singh


I like this method:

using Newtonsoft.Json.Linq; //jsonString is your JSON-formatted string JObject jsonObj = JObject.Parse(jsonString); Dictionary<string, string> dictObj = jsonObj.ToObject<Dictionary<string, object>>(); 

You can now access anything you want using the dictObj as a dictionary. You can also use Dictionary<string, string> if you prefer to get the values as strings.

like image 45
Blairg23 Avatar answered Sep 17 '22 15:09

Blairg23