Deserialize JSON string to Dictionary<string,object>
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);
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.
The MSDN documentation for the as
keyword states that the statement expression as type
is equivalent to the statement expression is type ? (type)expression : (type)null
. If you run json.GetType()
it will return System.Object[]
and not System.Collections.Generic.Dictionary
.
In cases like these where the type of object into which I want to deserialize a json object is complex, I use an API like Json.NET. You can write your own deserializer as:
class DictionaryConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
Throw(new NotImplementedException());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// Your code to deserialize the json into a dictionary object.
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Throw(new NotImplementedException());
}
}
And then you can use this serializer to read the json into your dictionary object. Here's an example.