I’m trying to create a Client library that will allow users to push serialized data to a service.
so I created a class
public class Data
{
public string Prop1 {get; set;}
public SubData Prop2 {get; set;}
}
public abstract class SubData
{
public string Prop3 {get; set;}
}
I would like to allow users to extend that SubData to add custom properties. but I’m having issues in my Serialization, it doesn’t serialize the properties of the extended inner object
JsonSerializer.Serialize(data)
I know that I could decorate my SubData class with JsonDerivedType attribute, but my problem is that SubData is in a package, and it doesn’t know about who will extend it and with what (and it doesn’t care)
I don’t know if I’m clear what my problem is so here is a full test to replicate:
using System.Text.Json;
public class Data
{
public string Prop1 { get; set; }
public SubData SubData { get; set; }
}
public abstract class SubData
{
public string Prop2 { get; set; }
}
public class ExtendedSubData : SubData
{
public string Prop3 { get; set; }
}
var data = new Data
{
Prop1 = "1",
SubData = new ExtendedSubData
{
Prop2 = "2",
Prop3 = "3"
}
};
SerializData(data);
void SerializData(Data data)
{
var serialized = JsonSerializer.Serialize<object>(data);
// serialized at this point doesn't contain Prop3 of
// ExtendedSubData
}
2
Answers
The issue you’re facing is that the JsonSerializer doesn’t know about the existence of ExtendedSubData and its additional properties because it’s not explicitly referenced in the serialization process
As an alternative to the custom
JsonConverter
, you can replace theSubData
property with genericTest it on dotnetfiddle:
https://dotnetfiddle.net/lkOM0Z