6

Lets assume I have like this property which I use to save/load settings:

public Options RectangleCaptureOptions { get; set; }

and I want to change property name to RegionCaptureOptions instead of RectangleCaptureOptions. But if I change name of property then Json .NET won't be able find it to deserialize.

Accepted answer here won't work:

.NET NewtonSoft JSON deserialize map to a different property name

Because if I use JsonProperty:

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

Then it will also serialize property as RectangleCaptureOptions which is old name.

So when I change name of variable or property still want to support old naming of them when deserializing (RegionCaptureOptions or RectangleCaptureOptions for this example) but use current name when serializing (RegionCaptureOptions). That way I can have backward compatibility support for my settings json file while loading (deserializing) them.

I think most clean solution would be making custom attribute such as JsonAlternativeName and using it like this:

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

Optionally it can have multiple parameter support, that way you can add multiple alternative names.

But not sure how to accomplish it (or is it possible at all) and can't find similar solution in StackOverflow because in each questions I found, people suggests using JsonProperty which not helps in my case.

Community
  • 1
  • 1
Jaex
  • 4,204
  • 2
  • 34
  • 56
  • Looks like a duplicate of [json deserialize from legacy property names](https://stackoverflow.com/questions/33155458/json-deserialize-from-legacy-property-names). But [Alternate property name while deserializing](http://stackoverflow.com/questions/19792274/alternate-property-name-while-deserializing) is very close also – dbc Jun 22 '16 at 08:11

0 Answers0