
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.
public GsonBuilder setVersion(double ignoreVersionsAfter)
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)<strong>
</strong> public String lastName;
}Version 1.0:
{
"firstName": "Raja"
}
Version 2.0:
{
"firstName": "Raja",
"lastName": "Ramesh"
}以上就是如何在Java中配置Gson以启用版本支持?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号