Home > Software design >  Updating the name of a Json Property in a class
Updating the name of a Json Property in a class

Time:10-21

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?

CodePudding user response:

This works using System.Text.Json.

            var foo = new myClass()
            {
                OldName = { "test" },
            };

            var bar = JsonSerializer.Serialize<myClass>(foo);
            var result = JsonSerializer.Deserialize<myClass>(bar);

CodePudding user response:

Try this

var foo = "{\"OldName\":[\"old test\"]}";
var fooN = "{\"NewName\":[\"new test\"]}";
var result = JsonConvert.DeserializeObject(foo, typeof(myClass));
//or
var result = JsonConvert.DeserializeObject(fooN, typeof(myClass));

var json = JsonConvert.SerializeObject(result);

json result:

{"NewName":["new test"]}
//or
{"NewName":["old test"]}

class

public class myClass
{
   [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<string> OldName {

        get {return null; }
        set {NewName=value;} 
    }

    public List<string> NewName {get; set;}
}
    
  • Related