Shmoopy
Shmoopy

Reputation: 5534

How to accept multiple names for a single property on newtonsoft JSON de-serialization?

We have a standard json format that we defined (the typo is on purpose):

{
  "Name" : "John",
  "Salari" : "150000"
}

which is de-serialized (using newtonsoft) to:

class Person
{
    public string Name;
    public string Salari;
}

Is there a way to change Salari to Salary and still be able to accept messages with the old name? Something like:

class Person
{
    public string Name;
    [DeserializeAlso("Salari")]
    public string Salary;
}

To make newtonsoft de-serializer understand that Salari should be de-serialized to the Salary field?

Upvotes: 2

Views: 1056

Answers (1)

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22054

You can make use of properties:

class Person
{
  protected string _Salary;
  public string Salary
  {
    get { return _Salary; }
    set { _Salary = value; }
  }
  public string Name { get; set; } 
}

class BackwardCompatiblePerson : Person
{
  public string Salari 
  {
    get { return _Salary; }
    set { _Salary = value; }
  }
}

And use Person for serialization & BackwardCompatiblePerson for deserialization.

Upvotes: 3

Related Questions