0

How to "virtually" add Json attribute to an existing class?
or more precisly
How is it posible to change the serialize behavior for a single property w/o creating a converter for the whole class and w/o rewriting/wrap the the whole class?

If it would be my own class I would just apply one of the json attributes.
If this is not (yet) possible with system.text.json (.NET6) how is it with Newtonsoft.Json?

Kux
  • 1,362
  • 1
  • 16
  • 31
  • With Json.NET you can add a synthetic property to an existing class or set of classes using a custom contract resolver. See e.g. [Json.net Add property to every class containing of a certain type](https://stackoverflow.com/q/46549680). But System.Text.Json does not make its contract information public, see [System.Text.Json API is there something like IContractResolver](https://stackoverflow.com/q/58926112/3744182), so you would need to create a DTO or converter, which you don't want to do. – dbc May 28 '22 at 04:39
  • You could make the converter generic -- i.e. basically maintain its own contract information. I think [Dahomey.Json](https://github.com/dahomey-technologies/Dahomey.Json) does this e.g. when supporting data contract attributes. But you would have to write this generic converter yourself, there's no extension point corresponding to `DefaultContractResolver` to inject modifications to object contracts. – dbc May 28 '22 at 04:39
  • @dbc thx. I feared it. Every time I start with system.text.json I get stuck with it. I am almost ready to write my own default JsonConverter. using reflection and supporting TypeDiscriptor, but I do not want to reinvent the wheel and actually I would expect something like this in the framework. I will research further... – Kux May 28 '22 at 05:01

0 Answers0