Json.Net没有正确地序列化版本类型

时间:2015-02-03 17:04:48

标签: c# json serialization json.net deserialization

当我序列化没有指定修订版本或内部版本号的Version对象时,无法对其进行反序列化。有没有人见过这个?

这是我的代码:

JsonSerializerSettings JsonSettings = new JsonSerializerSettings()
        {
            TypeNameHandling = TypeNameHandling.Objects,
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
            DateTimeZoneHandling = DateTimeZoneHandling.Utc,
            NullValueHandling = NullValueHandling.Ignore
        };


var ver = new Version(1000, 1);
var str = JsonConvert.SerializeObject(ver, Newtonsoft.Json.Formatting.Indented, JsonSettings);
var ver2 = JsonConvert.DeserializeObject(str, JsonSettings);

这实际上是有道理的,因为json字符串是:

{
    "$type": "System.Version, mscorlib",
    "Major": 1000,
    "Minor": 1,
    "Build": -1,
    "Revision": -1,
    "MajorRevision": -1,
    "MinorRevision": -1
}

在没有设置修订和构建的情况下,我是否仍然反序列化了这个?

1 个答案:

答案 0 :(得分:2)

由于System.Version没有默认构造函数,因此您需要使用自定义转换器:

public class VersionConverter : JsonConverter
{
    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        JObject obj = serializer.Deserialize<JObject>(reader);

        int major = obj["Major"].ToObject<int>();
        int minor = obj["Minor"].ToObject<int>();

        Version v = new Version(major, minor);

        return v;
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(Version).IsAssignableFrom(objectType);
    }

    public override bool CanWrite { get { return false; } }
}

(请注意,您可以对其进行扩展,以类似的方式考虑其他参数,例如buildrevision

用法:

JsonSerializerSettings JsonSettings = new JsonSerializerSettings()
{
    TypeNameHandling = TypeNameHandling.Objects,
    DateFormatHandling = DateFormatHandling.IsoDateFormat,
    DateTimeZoneHandling = DateTimeZoneHandling.Utc,
    NullValueHandling = NullValueHandling.Ignore,
    Converters = new[] { new VersionConverter() }
};


var ver = new Version(1000, 1);
var str = JsonConvert.SerializeObject(
              ver, Newtonsoft.Json.Formatting.Indented, JsonSettings);

var ver2 = JsonConvert.DeserializeObject<Version>(str, JsonSettings);