I am trying to update the name of a property in a Json serializable class that is already released, so I need to make it backwards compatible.
public class myClass
{
//[JsonIgnore] - now old json files can't be read, so this won't work...
//[JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Error)] - didn't do anything
//[JsonProperty(nameof(NewName)] - throws error - "That already exists"
[Obselete("Use NewName instead")]
public List<string> OldName { get => newName; set => newName = value; }
public List<string> NewName { get; set; } = new List<string>();
}
And I use it like this:
[Test]
public void test()
{
var foo = new myClass()
{
OldName = { "test" },
};
var bar = JsonConvert.SerializeObject(foo);
var result = JsonConvert.DeserializeObject(bar, typeof(myClass));
}
When I look at the value in result.NewName, I find this list: {"test", "test"}
, but I expected this list: {"test"}
The desired behavior:
- If someone is already using OldName in their code, they get an obselete warning
- if someone parses an old json file with OldName in it, it's correctly mapped to NewName
- New json files that are created use NewName, and OldName isn't found anywhere in the json file
- In no case is the value deserialized twice and put in the same list
How would you accomplish this?