C# – Deserialize Dictionary with JSON.NET

asp.net-web-apicjsonjson.netnet

I am using Newtonsoft.Json with version 4.0.8 and trying to use it with Web API.
So I wanted to deserialize JSON with

JsonConvert.DeserializeObject<AClass>(jsonString);

This works until I added a Dictionary as property to this class and wanted to deserialize it.

The json string is in the form of

{ 
   "Date":null,
   "AString":"message",
   "Attributes":[
                   {"Key":"key1","Value":"value1"},      
                   {"Key":"key2","Value":"value2"}
                ],
    "Id":0,
    "Description":"...
}

When deserializing exception of type JsonSerializationException occures with message: "Cannot deserialize JSON array into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'."

What am I doing wrong here?

UPDATE1:
When serializing with JSON.NET i get the following for the dictionary:

Attributes":{"key1":"value1","key2":"value2"}

Seems that WebApi deserializes the object in an other way than Json.Net would.
Server side I use following line for implicit deserializing:

return new HttpResponseMessage<AClass>(object);

UPDATE2:
As a workaround I came now to following line server side.

return new HttpResponseMessage<string>(JsonConvert.SerializeObject(license).Base64Encode());

I convert it with Json.Net server side and transfer it as base64 encoded string. So Json.Net can deserialize its own format.

But its still not that what I want, so are thery any further suggestions?

Best Answer

It should work if you declare Attributes as List<KeyValuePair<string, string>>