I am using a public library that exposes a model for SwaggerDocument. It comes with some serialization logic added via annotations to specify what should be ignored during serialization, and what order should be applied during serialization and deserialization:
[Newtonsoft.Json.JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 6, PropertyName = "basePath")]
public string BasePath;
I want to change these annotations, without having to creating my own class with all the other logic copied over. Can I extend this class and override the annotations? E.g.
MySwaggerDocument: SwaggerDocument
{
@override
[Newtonsoft.Json.JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate, Order = 4, PropertyName = "basePath")]
public string BasePath;
}
It is not an ideal solution, although this works.
You could use the following strategy to expose some of the attributes of the base class which are messing up the order in your custom derived class.
The drawback is to declare some of the base class' attributes, but as you can see, the logic behind this is quite simple (the get/set syntax is C# 7.0).
using Newtonsoft.Json;
using System;
namespace JsonTest
{
public class Base
{
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 1, PropertyName = "A")]
public string A { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 2, PropertyName = "X")]
public string X { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 3, PropertyName = "B")]
public string B { get; set; }
}
public class Derived : Base
{
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 4, PropertyName = "C")]
public string C { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 5, PropertyName = "X")]
public new string X
{
get => base.X;
set => base.X = value;
}
[JsonProperty(DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate, Order = 6, PropertyName = "D")]
public string D { get; set; }
}
class Program
{
static void Main(string[] args)
{
Base b = new Base() { A = "a", B = "b", X = "x" };
string serB = JsonConvert.SerializeObject(b);
Console.WriteLine($"Serialized base class:\r\n {serB}");
Derived d = new Derived() { A = "a", B = "b", C = "c", D = "d", X = "x" };
string serD = JsonConvert.SerializeObject(d);
Console.WriteLine($"Serialized derived class:\r\n {serD}");
}
}
}
Output:
Serialized base class:
{"A":"a","X":"x","B":"b"}
Serialized derived class:
{"A":"a","B":"b","C":"c","X":"x","D":"d"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With