反序列化Dicionary与JSON.NET
我使用Newtonsoft.Json与4.0.8版本,并试图用它的Web API。 所以我想反序列化的JSON与
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.
JSON字符串是形式
The json string is in the form of
{
"Date":null,
"AString":"message",
"Attributes":[
{"Key":"key1","Value":"value1"},
{"Key":"key2","Value":"value2"}
],
"Id":0,
"Description":"...
}
在反序列化异常类型 JsonSerializationException
occures与消息:的无法反序列化JSON数组类型System.Collections.Generic.Dictionary`2 [ System.String,System.String]。的
When deserializing exception of type JsonSerializationException
occures with message: "Cannot deserialize JSON array into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'."
我在做什么错在这里?
UPDATE1: 我得到以下的字典时有JSON.NET序列化:
UPDATE1: When serializing with JSON.NET i get following for the dictionary:
Attributes":{"key1":"value1","key2":"value2"}
看来,的WebAPI反序列化对象比Json.Net会的其他方式。 服务器端我用下面的行隐式反序列化:
Seems that WebApi deserializes the object in an other way than Json.Net would. Server side i use following line to for implicit deserializing:
return new HttpResponseMessage<AClass>(object);
UPDATE2: 作为一种变通方法我现在来到了下面的行服务器端。
UPDATE2: As a workaround i came now to following line server side.
return new HttpResponseMessage<string>(JsonConvert.SerializeObject(license).Base64Encode());
我将它转换与Json.Net服务器端,并将其转移为base64 EN codeD字符串。所以Json.Net可以反序列化自己的格式。
I convert it with Json.Net server side and transfer it as base64 encoded string. So Json.Net can deserialize its own format.
但它仍然不正是我想要的,所以是thery任何进一步的建议?
But its still not that what i want, so are thery any further suggestions?
它应该工作,如果你声明属性
为名单,其中,KeyValuePair&LT;字符串,字符串&GT;&GT;
It should work if you declare Attributes
as List<KeyValuePair<string, string>>