5

First of all; I'm using Newtonsoft.Json to deserialize JSON into objects like this:

JSON:

[{"number":22041}]

Order Object

[JsonProperty("number")]
public string OrderNumber { get; set; }

However, depending on which version the 'other' side is on, the Json may change into

[{"order_number":22041}]

So I'd actually like to pre-define "number" and "order_number" to both deserialize into my OrderNumber.

Is there a way to achieve something like the following (that actually works)

[JsonProperty("order_number")]
[JsonProperty("number")]
public string OrderNumber { get; set; }

I could write another class that has the same properties but with other JsonProperties depending on the Version they are on, but that seems like something to try last, unless there is no possible way to do this easier.


Update

I agree that this question is a duplicate of the question above. However since the given keys in the JSON changes significantly, I will be making duplicate objects (OrderV1 , OrderV2 as example).

Simply replacing some characters into other ones will not be enough in my case.

Paramone
  • 2,634
  • 4
  • 31
  • 58
  • 1
    Too bad (or: luckily) that C# doesn't have [unions](http://en.cppreference.com/w/cpp/language/union). – Uwe Keim Oct 09 '17 at 12:53
  • Have you tried using [Obsolete]-marked properties for the older versions that access the newer properties in their setters and getters? – Danny Varod Oct 09 '17 at 12:54
  • 1
    @UweKeim That would make it easier (or even worse) indeed! ;) – Paramone Oct 09 '17 at 12:54
  • Or alternatively, use different classes for different API versions, then transform them into the newer class. (You can use Omu.ValueInjector to help with identical properties.) – Danny Varod Oct 09 '17 at 12:56
  • 1
    you should create a custom JSONConverter trying to match the property name. This answer can give you some idea: https://stackoverflow.com/questions/19792274/alternate-property-name-while-deserializing/19885911#19885911 Why don't you convert the JSON to a string, replacing "order_number": to "number":? – Giox Oct 09 '17 at 12:57
  • @Giox Thank you! I will give this a shot before! – Paramone Oct 09 '17 at 12:59
  • In addition to the marked duplicate, there's also [json deserialize from legacy property names](https://stackoverflow.com/q/33155458/3744182). – dbc Oct 10 '17 at 11:34

0 Answers0