Json.NET backward compatibility: write a new property name, but read either the new or the old property

Suppose I have this property that I use to save / load settings:

public Options RectangleCaptureOptions { get; set; }

and I want to change the name of the property to RegionCaptureOptionsinstead RectangleCaptureOptions. But if I change the name of the property, then Json.NET will not be able to find it for deserialization.

The accepted answer here will not work:

.NET NewtonSoft JSON deserializes map for another property name

Because if I use JsonProperty:

[JsonProperty("RectangleCaptureOptions")]
public Options RegionCaptureOptions { get; set; }

Then it will also serialize the property as RectangleCaptureOptions, the old name.

Therefore, when I change the name of a variable or property, I still want to maintain their old name when deserializing ( RegionCaptureOptionsor RectangleCaptureOptionsfor this example), but when serializing ( RegionCaptureOptions) use the current name. That way, I can have backward compatibility support for my json file settings when loading (deserializing) them.

I think the cleanest solution would be to create a custom attribute, such as JsonAlternativeName, and use it like this:

[JsonAlternativeName("RectangleCaptureOptions")]
public Options RegionCaptureOptions { get; set; }

Optionally, it may have support for multiple parameters, so you can add several alternative names.

, ( ), StackOverflow, , , JsonProperty, .

+4

All Articles