Json.Net未正确序列化版本类型



序列化没有指定修订版或内部版本号的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
}

我是否可以在不设置"修订版"one_answers"内部版本"的情况下对此进行反序列化?

由于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); 

相关内容

  • 没有找到相关文章

最新更新