Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json Deserialization of form Dictionary<string, Dictionary<string, string>>

Tags:

json

c#

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?

like image 407
barry Avatar asked Sep 15 '26 01:09

barry


1 Answers

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));
like image 52
L.B Avatar answered Sep 17 '26 14:09

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!