在Java中使用Gson时,什么时候需要使用@SerializedName注解?

语法

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

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;
   }
}

Output

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

以上就是在Java中使用Gson时,什么时候需要使用@SerializedName注解?的详细内容,更多请关注其它相关文章!