Why System.Version in JSON string does not deserialize correctly?

本小妞迷上赌 提交于 2019-12-04 22:41:48

The Newtonsoft.Json library provides a set of common converters in the Newtonsoft.Json.Convertersnamespace, including a VersionConverter you can use to serialize and deserialize System.Version.

Note that you have to use the VersionConverterboth for serialization and deserialization, though.
That's because standard serialization would generate eg.:{"Major":1,"Minor":2,"Build":3,"Revision":0,"MajorRevision":0,"MinorRevision":0} while VersionConverterdeserialization expects a simple string as in "1.2.3".

So usage would be:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;  

string s = JsonConvert.SerializeObject(version, new VersionConverter());
Version v = JsonConvert.DeserializeObject<Version>(s, new VersionConverter());

I'm not sure what's the first version of Newtonsoft.Jsonthat includes that converter. Mine has it and it's 5.0.6.

The properties of the Version class have no setter. They just return the value of their corresponding private fields. Therefore, the deserializer is not able to change their values.

But with Json.NET you can write a custom converter class which handles the deserialization of the Version class.

Beware: This code has not been tested very well...

public class VersionConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // default serialization
        serializer.Serialize(writer, value);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // create a new Version instance and pass the properties to the constructor
        // (you may also use dynamics if you like)
        var dict = serializer.Deserialize<Dictionary<string, int>>(reader);
        return new Version(dict["Major"], dict["Minor"], dict["Build"], dict["Revision"]);
    }

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

Then you have to specify that you want to use the converter:

var v = new Version(1, 2, 3, 4);
string json = JsonConvert.SerializeObject(v);

var v2 = JsonConvert.DeserializeObject<Version>(json, new VersionConverter());

Json.NET decides itself whether to use one of the converters you specified. So you can always specify the converter, as shown below. Json.NET will use one of your converters if they match a type within SomeClass.

var result = JsonConvert.DeserializeObject<SomeClass>(json, new VersionConverter());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!