如何在Java中配置Gson以启用版本支持?
2026-02-20 10:41 来源:西西软件网 作者:佚名
The Gson library provides a simple versioning system for the Java objects that it reads and writes and also provides an annotation named @Since for the versioning concept @Since(versionnumber).
We can create a Gson instance with versioning using the GsonBuilder().setVersion() method. If we mentioned like setVersion(2.0), means that all the fields having 2.0 or less are eligible to parse.
Syntax
public GsonBuilder setVersion(double ignoreVersionsAfter)
Example
import com.google.gson.*;
import com.google.gson.annotations.*;
public class VersionSupportTest {
public static void main(String[] args) {
Person person = new Person();
person.firstName = "Raja";
person.lastName = "Ramesh";
Gson gson1 = new GsonBuilder().setVersion(1.0).setPrettyPrinting().create();
System.out.println("Version 1.0:");
System.out.println(gson1.toJson(person));
Gson gson2 = new GsonBuilder().setVersion(2.0).setPrettyPrinting().create();
System.out.println("Version 2.0:");
System.out.println(gson2.toJson(person));
}
}
// Person class
class Person {
@Since(1.0)
public String firstName;
@Since(2.0)
public String lastName;
}输出
Version 1.0:
{
"firstName": "Raja"
}
Version 2.0:
{
"firstName": "Raja",
"lastName": "Ramesh"
}
上面就是如何在Java中配置Gson以启用版本支持?的内容了,文章的版权归原作者所有,如有侵犯您的权利,请及时联系本站删除,更多相关淘客帝国的资讯,请关注收藏西西下载站。
下一篇:返回列表