问题描述
我正在使用版本4.0.8的Newtonsoft.Json,并尝试将其与Web API一起使用.所以我想用
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);
这是可行的,直到我将Dictionary作为属性添加到此类并希望反序列化它.
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
的反序列化异常发生并出现以下消息时:" 无法将JSON数组反序列化为类型'System.Collections.Generic.Dictionary`2 [System.String,System.String]'. /em> "
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 the 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 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编码的字符串进行传输.因此,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.
但是它仍然不是我想要的,理论上有什么进一步的建议吗?
But its still not that what I want, so are thery any further suggestions?
推荐答案
如果将Attributes
声明为List<KeyValuePair<string, string>>
这篇关于使用JSON.NET反序列化字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!