I work with a class that comes from a Nuget package, and therefore I can’t add properties to it.
Imagine this class:
public class Base
{
public Data Data { get; set; }
// Many other properties..
}
public class Data
{
public string Value1 { get; set; }
// Many other properties..
}
The JSON payloads I work with look like this:
{
Data:
{
"Value1": "some value...",
"Value2": "some other value...",
// Many other properties...
}
}
In other words, the JSON payloads contain a property that does not exist in the Nuget’s class – Value2
.
I am looking for a way to deserialize the above JSON into a class, in a way that gives me access both to Base
and its properties, and to Value2
.
I am also in need of doing this both using Newtonsoft
and System.Text.Json
libraries.
I have tried creating a derived class, with a nested JsonProperty
attribute ("Data/Value2") but that doesn’t work with either library:
public class Derived : Base
{
[JsonProperty("Data/Value2")]
[JsonPropertyName("Data/Value2")]
public string Value2 { get; set; }
}
I have tried overriding Data
with in a derived class – that works in Newtonsoft but I lose the base class’s Data
, and it is not supported at all in System.Text.Json:
public class Derived : Base
{
[JsonProperty("Data")]
[JsonPropertyName("Data")]
public Data Data2 { get; set; }
}
I have tried playing with some custom converters but haven’t been able to find a working solution.
What is the way to support an extra property (one that can’t be added to the class because it’s external), without losing access to the class’s existing properties, for both Newtonsoft and System.Text.Json libraries?
2
Answers
Ended up using a DTO, as suggested in the comments. This appears to be required, at least until a new, relevant version of the Nuget is realeased.
I would not go with this approach, but will post for educational purposes.
as mentioned in comments it would be simpler to serialize to class and map to another one.
this example is showing Custom Json Converter .
P.S. i wrote in a way, than you can put multiple Values3,4 etc. (still stiff code)