I have encountered a problem serialising an object to JSON.
The object is set up with serialisable fields and properties, but it also implements a generic collection interface:
In a simplified form, it essentially looks like this:
class MyClass : IEnumerable<IMyInterface>
{
[JsonConstructor] public MyClass {}
[JsonInclude] public List<MyObj> Entries { get; set; } = new List<MyObj> ();
}
class MyObj : IMyInterface
{
[JsonInclude] public string strValue;
[JsonIgnore] public bool ExampleProp => false;
}
public interface IMyInterface
{
string strValue;
bool ExampleProp { get; }
}
The problem arises because Text.Json.JsonSerializer.Serialize seems to choose to serialise the MyClass instance as an IEnumerable - thus ending up including the ExampleProp value - rather than as a MyClass object.
I have not been able to identify any way to control this behaviour; my only option seems to be to refactor and eliminate the IEnumerable interface (e.g. bury it in a property or method).
Does anyone know of some way to control how JsonSerializer makes these choices?