Zeus82
Zeus82

Reputation: 6375

Json.Net Not Serializing Version Type properly

When I serialize a Version object that does not have a revision or build number specified, it cannot be deserialized. Has anyone seen this before?

Here is my code:

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

This actually makes sense because the json string is:

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

Is there anyway for me to deserialize this without setting Revision and Build?

Upvotes: 2

Views: 2326

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

Since System.Version does not have a default constructor, you'll need to use a custom converter:

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; } }
}

(Note that you could expand this to take into account the other parameters like build and revision in a similar way)

Usage:

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

Upvotes: 2

Related Questions