Home > Java > javaTutorial > body text

How to rename properties of JSON using Gson in Java?

WBOY
Release: 2023-08-27 14:01:06
forward
740 people have browsed it

How to rename properties of JSON using Gson in Java?

Gson @SerializedName Notes Can be serialized to JSON with the provided name value as its field name. This annotation can override any FieldNamingPolicy, including the default field naming policy that may have been set on the Gson instance. Different naming strategies can be set using the GsonBuilder class.

Syntax

@Retention(value=RUNTIME)
@Target(value={FIELD,METHOD})
public @interface SerializedName
Copy after login

Example

import com.google.gson.annotations.*;
import com.google.gson.*;
public class SerializedNameAnnotationTest {
   public static void main(String args[]) {
      Employee emp = new Employee("Rahul", "Dev", 30, "Nagpur");
      <strong>Gson </strong>gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print
      String jsonStr = gson.toJson(emp);
      System.out.println(jsonStr);
   }
}
// Employee class
class Employee {
   @SerializedName("first_name")
   private String firstName;
   @SerializedName("last_name")<strong>
</strong>   private String lastName;
   private int age;
   private String address;
   public Employee() {
   }
   public Employee(String firstName, String lastName, int age, String address) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }
   public String getFirstName() {
      return firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public int getAge() {
      return age;
   }
   public String getAddress() {
      return address;
   }
}
Copy after login

Output

{
 "first_name": "Rahul",
 "last_name": "Dev",
 "age": 30,
 "address": "Nagpur"
}
Copy after login

The above is the detailed content of How to rename properties of JSON using Gson in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!