Customizing JSON serialization

Source: Internet
Author: User

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

  1. 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; }}
  2. 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.
  3. 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();    }}
  4. Mark our Type

    public class RootObj{    [JsonConverter(typeof(JC<A>))]    public A A { get; set; }}
  5. run! Then we can see that the results are the same as we expected:)

Source Code Transmission Door

Customizing JSON serialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.