1

I have a lot of objects (type A) that contain a field which is a very large object itself (type B).

When I serialize objects of type A, I don't want to include the contents of B but I want to replace that field by a string.

I understand I can make a custom serializer but the serialization is done through an object that is passed to me (based on json.net), so I can't initialize my own serializer at that level in the call hierarchy and the type in question is not known where the serializer is initialized.

I saw that you can make serialization conditional by including a method in the object itself ("ShouldSerialize<fieldname> : bool) and I was wondering if there is a similar mechanism to serialize a specific type with a custom serializer where I'd embed the serializer in the object definition.

Thomas
  • 10,933
  • 14
  • 65
  • 136
  • 2
    Take a look at the [JsonConverterAttribute](https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm#JsonConverterAttribute). – Lasse V. Karlsen Jun 26 '21 at 10:37
  • 2
    A different approach would be to embed a string property that converts to and from the object, and apply `[JsonIgnore]` on the object property. – Lasse V. Karlsen Jun 26 '21 at 10:38
  • 1
    the jsonignore + adding a property seems to to be the simplest. Thanks! – Thomas Jun 26 '21 at 13:56
  • 1
    Since it seems your problem was resolved, I closed this off as a duplicate. For string property + `[JsonIgnore]` see [Unwrapped property in C# JSON](https://stackoverflow.com/q/27681377/3744182). For `JsonConverter` on a property that serializes an object as a string, see [custom serializer for just one property in Json.NET](https://stackoverflow.com/q/18521970/3744182) + [Json.Net: Serialize/Deserialize property as a value, not as an object](https://stackoverflow.com/q/40480489/3744182). – dbc Jun 27 '21 at 17:02

0 Answers0