user1357872
user1357872

Reputation: 803

JSON string to dictionary object error

I have the below code in my C# program where I need to convert a json structure to a dictionary.

string json = @"[{""id"":""51851"",""name"":""test {""id"":""527"",""name"":""test1""}]"; 
    var json_serializer = new JavaScriptSerializer();
    Dictionary<string, object> dictionary = json_serializer.Deserialize<Dictionary<string, object>>(json);

while running this, I am getting the below error.

Type 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for deserialization of an array.

Can anyone help me to figure out what wrong in this?

Upvotes: 2

Views: 6049

Answers (3)

Oliver
Oliver

Reputation: 9002

This: "[{""id"":""518523721""}]" is an array of objects.

Remove the square braces so that you are left with:

"{""id"":""518523721""}"

This should then de-serialize to Dictionary<string, object>.

EDIT (based on comment below)

For multiple objects, the JSON is incorrect. the following JSON structure should de-serialize as you require:

"{
    "51851" : { "id" : "51851", "name" : "test" },
    "527" : { "id" : "527", "name" : "test" }
}"

Upvotes: 1

Matthew
Matthew

Reputation: 25773

Your JSON represents an array of objects, not a dictionary.

If your JSON is incorrect (you didn't intend on an array) you can remove the square brackets and your code should work.

Otherwise, you change the code to what you're deserializing.

var dictionaries = json_serializer.Deserialize<List<Dictionary<string, object>>>(json);

foreach (var dictionary in dictionaries)
{
    Console.WriteLine(dictionary["id"]); // 518523721
}

Upvotes: 0

Jay Patel
Jay Patel

Reputation: 647

Try this. Instead of object use dynamic for integer.

Dictionary<string, dynamic> dictionary = json_serializer.Deserialize<Dictionary<string, dynamic>>(json)

Also as Oliver mentioned, remove the square brackets. It is used for arrays.

Upvotes: 0

Related Questions