0

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?

Loophole
  • 333
  • 4
  • 7
  • 1
    This is not currently implemented as of .NET 7. You will need to create a custom converter or refactor your design. See [System.Text.Json: How to serialise an IEnumerable like a regular class?](https://stackoverflow.com/q/74615202). – dbc Mar 24 '23 at 03:20
  • 1
    How many times it was told that anybody who decided to use a collection as a basic class is looking for the problems. – Serge Mar 24 '23 at 12:20
  • 1
    Also, see [Why not inherit from List](https://stackoverflow.com/q/21692193) for reasons why the design should be refactored. – dbc Mar 24 '23 at 13:57
  • Thank you, @dbc; some very useful pointers there. – Loophole Mar 26 '23 at 23:10

0 Answers0