Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
652 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...