How to serialize only inherited class properties using JsonConverter

I am trying to serialize only inherited class properties using json.net. I know about the [JsonIgnore] attribute, but I just want to ignore them for a specific case, so I used a custom JsonConverter instead.

Here is my class:

public class EverythingButBaseJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Find properties of inherited class
        var classType = value.GetType();
        var classProps = classType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();

        // Remove the overrided properties
        classProps.RemoveAll(t =>
        {
            var getMethod = t.GetGetMethod(false);
            return (getMethod.GetBaseDefinition() != getMethod);
        });

        // Get json data
        var o = (JObject)JToken.FromObject(value);

        // Write only properties from inhertied class
        foreach (var p in o.Properties().Where(p => classProps.Select(t => t.Name).Contains(p.Name)))
            p.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException("");
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
}

When doing a simple o.WriteTo (writer); it gives the same result as without the use of a converter. When repeating properties and using WriteTo for properties, it works great for the base type (int, string, etc.), but I have a problem with collections.

Expected:

{
  "Type": 128,
  "Time": [
    1,
    2,
  ],
  "Pattern": 1,
  "Description": ""
}

Got:

  "Type": 128,
  "Time": [
    1,
    2,
  ]"Pattern": 1,
  "Description": ""

As you can see, the "," and "endline" snippet is missing from the collection. I also skip global {} for the whole object.

? , ?

0
1

, (, Json.NET?). , , JObject :

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Find properties of inherited class
        var classType = value.GetType();
        var classProps = classType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();

        // Remove the overrided properties
        classProps.RemoveAll(t =>
        {
            var getMethod = t.GetGetMethod(false);
            return (getMethod.GetBaseDefinition() != getMethod);
        });

        // Get json data
        var o = (JObject)JToken.FromObject(value);

        // Remove all base properties
        foreach (var p in o.Properties().Where(p => !classProps.Select(t => t.Name).Contains(p.Name)).ToList())
            p.Remove();

        o.WriteTo(writer);
    }

:

public class EverythingButBaseContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        if (member.ReflectedType != member.DeclaringType)
            return null;
        if (member is PropertyInfo)
        {
            var getMethod = ((PropertyInfo)member).GetGetMethod(false);
            if (getMethod.GetBaseDefinition() != getMethod)
                return null;
        }
        var property = base.CreateProperty(member, memberSerialization);
        return property;
    }
}

:

        var settings = new JsonSerializerSettings { ContractResolver = new EverythingButBaseContractResolver() };
        var json = JsonConvert.SerializeObject(rootObject, Formatting.Indented, settings);
+2

Source: https://habr.com/ru/post/1678861/


All Articles