We have some configuration files which were generated by serializing C# objects with Json.net.
We'd like to migrate one property of the serialised class away from being a simple enum property into a class property.
One easy way to do this, would be to leave the old enum property on the class, and arrange for Json.net to read this property when we load the config, but not to save it again when we next serialize the object. We'll deal with generating the new class from the old enum separately.
Is there any simple way to mark (e.g. with attributes) a property of a C# object, so that Json.net will ignore it ONLY when serializing, but attend to it when deserializing?
Best Answer
There are actually several fairly simple approaches you can use to achieve the result you want.
Let's assume, for example, that you have your classes currently defined like this:
And you want to do this:
To get this:
Approach 1: Add a ShouldSerialize method
Json.NET has the ability to conditionally serialize properties by looking for corresponding
ShouldSerialize
methods in the class.To use this feature, add a boolean
ShouldSerializeBlah()
method to your class whereBlah
is replaced with the name of the property that you do not want to serialize. Make the implementation of this method always returnfalse
.Note: if you like this approach but you don't want to muddy up the public interface of your class by introducing a
ShouldSerialize
method, you can use anIContractResolver
to do the same thing programmatically. See Conditional Property Serialization in the documentation.Approach 2: Manipulate the JSON with JObjects
Instead of using
JsonConvert.SerializeObject
to do the serialization, load the config object into aJObject
, then simply remove the unwanted property from the JSON before writing it out. It's just a couple of extra lines of code.Approach 3: Clever (ab)use of attributes
[JsonIgnore]
attribute to the property that you do not want to be serialized.[JsonProperty]
attribute to the alternate setter, giving it the same JSON name as the original property.Here is the revised
Config
class: