Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

c# - Deserialize Dictionary with JSON.NET

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...