Home > Java > javaTutorial > How to configure Gson in Java to enable version support?

How to configure Gson in Java to enable version support?

PHPz
Release: 2023-08-20 22:45:07
forward
670 people have browsed it

How to configure Gson in Java to enable version support?

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)
Copy after login

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)<strong>
</strong>   public String lastName;
}
Copy after login

输出

Version 1.0:
{
 "firstName": "Raja"
}
Version 2.0:
{
 "firstName": "Raja",
 "lastName": "Ramesh"
}
Copy after login

The above is the detailed content of How to configure Gson in Java to enable version support?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template