Custom JsonConverter<T> |
This sample creates a custom converter from JsonConverter<T> that overrides serialization for the Version class with a custom display string.
public class VersionConverter : JsonConverter<Version> { public override void WriteJson(JsonWriter writer, Version value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } public override Version ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer) { string s = (string)reader.Value; return new Version(s); } } public class NuGetPackage { public string PackageId { get; set; } public Version Version { get; set; } }
NuGetPackage p1 = new NuGetPackage { PackageId = "Newtonsoft.Json", Version = new Version(10, 0, 4) }; string json = JsonConvert.SerializeObject(p1, Formatting.Indented, new VersionConverter()); Console.WriteLine(json); // { // "PackageId": "Newtonsoft.Json", // "Version": "10.0.4" // } NuGetPackage p2 = JsonConvert.DeserializeObject<NuGetPackage>(json, new VersionConverter()); Console.WriteLine(p2.Version.ToString()); // 10.0.4