Is it possible to add a property to the JSON version of my class if it does not exist in the class?

I have a List<> objects. Their class does not have the "color" ( String ) property, but I can get the value of this property for each element of the list just before serialization.

Is this the only way to include this property in a JSON object, to add it to the class and then serialize it all?

Or is there a way / approach to adding a property that should appear in a JSON object that would otherwise be useless in my class?

I know that this is possible with all sorts of string manipulation methods, but that doesn't seem right.

I am using DataContractJsonSerializer .

+4
source share
2 answers

You can create a surrogate data transfer contract that transparently replaces instances of your class with instances of another class. This new class may look like anything, but in your case it will just have the additional Colour property.

The advantage is that you keep the original type of list items; surrogates are created during the serialization process, and your existing code should not touch them at all.

+3
source

I suppose you can create a new class that inherits from your list of objects and adds a line that is not used in the main class.

When creating JSON, simply use a derived class that will contain the added string value and inherit all other data from the original object.

+1
source

Source: https://habr.com/ru/post/1434564/


All Articles