I have a List<> of objects. Their class doesn’t have a ‘colour’ property (String) – but I can derive the value of this property for each list element right before serializing.
Is the only way to include this property in the JSON object to add it to the class and then serialize the whole thing?
Or is there a way/approach to adding a property that needs to appear in a JSON object that would otherwise be pretty useless in my class?
I know it’s possible with all sorts of string manipulation methods but it doesn’t feel right doing that.
I’m using DataContractJsonSerializer.
You can create a data contract surrogate that transparently substitutes instances of your class with instances of another class. This new class can look like anything, but in your case it would simply have the additional
Colourproperty.The benefit here is that you keep the original type of the list items; the surrogates get created during the serialization process and your existing code will not need to touch them at all.