I've recently been asked how to customize a JSON serialization so that when serializing, only the members of the parent class of the declaration are written, not the members of the actual subclass. Of course, serialization uses the most json.net that everyone uses.
Simply put, this is a contract how to resolve the problem, json.net choose to use the actual type naturally there are many considerations, after all, the declaration type can be abstract class or interface, etc. Nonsense not to say, directly on the code (for example, to be used in the production of the word need to deal with various edge cases).
-
Type relationship
public class RootObj{ public A A { get; set; }}public class A{ public string X { get; set; }}public class B : A{ public string Y { get; set; }}
-
Instance and serialization
var r = new RootObj { A = new B { X = "x", Y = "y" } };Console.WriteLine(JsonConvert.SerializeObject(r));
In the case of nothing change, the output is:
{"A":{"Y":"y","X":"x"}}
And the expectation is:
{"A":{"X":"x"}}
We expect to output only members of a.
-
Write your own jsonconverter:
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(); }}
-
Mark our Type
public class RootObj{ [JsonConverter(typeof(JC<A>))] public A A { get; set; }}
-
run! Then we can see that the results are the same as we expected:)
Source Code Transmission Door
Customizing JSON serialization