3

I'm trying to deserialize a json string of form [{"key" : "Microsoft", "value":[{"Key":"Publisher","Value":"abc"},{"Key":"UninstallString","Value":"c:\temp"}]} and so on ] to a C# object.

It is basically in the form Dicionary<string, Dictionary<string, string>>. I tried using the Newtonsoft's JsonConvert.Deserialize but got an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.String]]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.

Is there any other alternative way to do it?

4
  • 1
    Just use var obj = JsonConvert.DeserializeObject(...). It works for your json string Commented Jul 5, 2012 at 22:34
  • im doing this currently... string jsonString = json; (this contains the json in the format mentioned above) var values = JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string,string>>>(jsonString);........I still get the same error. Commented Jul 5, 2012 at 22:39
  • im doing this currently. Why don't you try the code i posted? I tested it and it works. Commented Jul 5, 2012 at 22:43
  • Thanks L.B.. But im looking for an object of type Dictionary<string,Dictionary<string,string>> because i already have a logic to loop through on such an object and insert those values into the database. Commented Jul 6, 2012 at 13:36

1 Answer 1

6

The best way I could find is:

string json = @"[{""Key"" : ""Microsoft"", ""Value"":[{""Key"":""Publisher"",""Value"":""abc""},{""Key"":""UninstallString"",""Value"":""c:\temp""}]}]";

var list = JsonConvert.DeserializeObject< List<KeyValuePair<string,List<KeyValuePair<string, string>>>> >(json);

var dict= list.ToDictionary(
         x => x.Key, 
         x => x.Value.ToDictionary(y=>y.Key,y=>y.Value));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.