Strategies for migrating serialized Json.NET document between versions/formats

后端 未结 2 594
囚心锁ツ
囚心锁ツ 2020-12-20 21:47

I\'m using Json.Net to serialize some application data. Of course, the application specs have slightly changed and we need to refactor some of the business object data. Wha

2条回答
  •  北海茫月
    2020-12-20 22:02

    You might find our library Migrations.Json.Net helpful

    https://github.com/Weingartner/Migrations.Json.Net

    A Simple example. Say you start with a class

    public class Person {
       public string Name {get;set}
    }
    

    and then you want to migrate to

    public class Person {
       public string FirstName {get;set}
       public string SecondName {get;set}
       public string Name => $"{FirstName} {SecondName}";
    }
    

    you would perhaps do the following migration

    public class Person {
       public string FirstName {get;set}
       public string SecondName {get;set}
       public string Name => $"{FirstName} {SecondName}";
    
       public void migrate_1(JToken token, JsonSerializer s){
          var name = token["Name"];
          var names = names.Split(" ");
          token["FirstName"] = names[0];
          token["SecondName"] = names[1];
          return token;
       }
    }
    

    The above glosses over some details but there is a full example on the homepage of the project. We use this extensively in two of our production projects. The example on the homepage has 13 migrations to a complex object that has changed over several years.

提交回复
热议问题