Json.NET 并不总是正确考虑ValueType
.Dictionary<KeyType,ValueType>
Dictionary<string,object>
如果一个值恰好是DefaultContractResolver.CanConvertToString()
返回 true 的值,除非我遗漏了一些东西,否则这使得序列化非常不可行。Rect
是 .NET 4.0 中的一种类型。我在 Json.NET 4.5r11 和 5.0r2 中试过这个。考虑以下代码:
_requestSerializerJson = new JsonSerializer();
// Even setting TypeNameHandling to All doesn't change the deserialized result
Dictionary<string, object> dictionary = new Dictionary<string, object>();
Rect a = new Rect(1, 2, 3, 4);
dictionary.Add("myrect", a);
byte[] bytes;
using (MemoryStream requestStream = new MemoryStream())
using (var streamWriter = new StreamWriter(requestStream))
using (var writer = new JsonTextWriter(streamWriter))
{
_requestSerializerJson.Serialize(writer, dictionary);
writer.Flush();
bytes = requestStream.ToArray();
}
// Serialized to: {"myrect":"1,2,3,4"}
using (MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length))
using (var textReader = new StreamReader(stream))
using (var reader = new JsonTextReader(textReader))
{
var b = _requestSerializerJson.Deserialize<Dictionary<string, object>>(reader);
}
// b is a Dictionary with a single *string* value "1,2,3,4" instead of a Rect!
我在想这个错误还是遗漏了什么?我刚刚从 XmlSerializer 切换到 Json.NET,因为它的性能令人难以置信(尤其是在构造时),而且它很容易过渡到,但是遇到这个问题让我有点害怕。
看起来如果 Json.NET 因为对象类型为CanConvertToString
() 返回 true 而要将某些东西写成字符串,它需要写出一个 Json 属性来指示发生了到字符串的转换,以便它可以可靠地“未转换”关于反序列化...