Created
July 27, 2018 05:28
-
-
Save vwxyzh/59e145aa61ded1eac2ba36c7ee91d7d4 to your computer and use it in GitHub Desktop.
Declaring type based JsonConverter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var r = new RootObj { A = new B { X = "x", Y = "y" } }; | |
Console.WriteLine(JsonConvert.SerializeObject(r)); | |
} | |
} | |
public class JC<T> : JsonConverter | |
{ | |
public override bool CanConvert(Type objectType) | |
{ | |
throw new NotImplementedException(); | |
} | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
throw new NotImplementedException(); | |
} | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
writer.WriteStartObject(); | |
var contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(typeof(T)); | |
foreach(var prop in contract.Properties) | |
{ | |
writer.WritePropertyName(prop.PropertyName); | |
serializer.Serialize(writer, prop.ValueProvider.GetValue(value)); | |
} | |
writer.WriteEndObject(); | |
} | |
} | |
public class RootObj | |
{ | |
[JsonConverter(typeof(JC<A>))] | |
public A A { get; set; } | |
} | |
public class A | |
{ | |
public string X { get; set; } | |
} | |
public class B : A | |
{ | |
public string Y { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment