Home > Java > javaTutorial > When using Gson in Java, when do you need to use the @SerializedName annotation?

When using Gson in Java, when do you need to use the @SerializedName annotation?

PHPz
Release: 2023-08-20 19:45:27
forward
1533 people have browsed it

When using Gson in Java, when do you need to use the @SerializedName annotation?

#@SerializedName annotation can be used to serialize a field to a different name instead of the actual field name. We can provide the expected serialization name as an annotation attribute and Gson can ensure that the field with the provided name is read or written.

Syntax

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

Example

import com.google.gson.*;
import com.google.gson.annotations.*;
public class SerializedNameTest {
   public static void main(String args[]) {
      <strong>Gson </strong>gson = new GsonBuilder().setPrettyPrinting().create();
      Person person = new Person(115, "Raja Ramesh", "Hyderabad");
      String jsonStr = gson.toJson(person);
      System.out.println(jsonStr);
   }
}
// Person class
class Person {
   @SerializedName("id")
   private int personId;
   @SerializedName("name")
   private String personName;
   private String personAddress;
   public Person(int personId, String personName, String personAddress) {
      this.personId = personId;
      this.personName = personName;
      this.personAddress = personAddress;
   }
   public int getPersonId() {
      return personId;
   }
   public String getPersonName() {
      return personName;
   }
   public String getPersonAddress() {
      return personAddress;
   }
}
Copy after login

Output

{
 "id": 115,
 "name": "Raja Ramesh",
 "personAddress": "Hyderabad"
}
Copy after login

The above is the detailed content of When using Gson in Java, when do you need to use the @SerializedName annotation?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template