Googleの@SerializedNameと@Expose注記


注記@SerializedNameのフィールドはJSONにシーケンス化され、出力されたJSON形式の名前が注記時に与えられた名前になります.
public class SomeClassWithFields {
   @SerializedName("name") private final String someField;
   private final String someOtherField;

   public SomeClassWithFields(String a, String b) {
     this.someField = a;
     this.someOtherField = b;
   }
 }
SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
 Gson gson = new Gson();
 String jsonRepresentation = gson.toJson(objectToSerialize);
 System.out.println(jsonRepresentation);

 ===== OUTPUT =====
 {"name":"a","someOtherField":"b"}

上はgoogle APIの例です.この注記はJSON形式でpojoクラス情報を出力する必要がある場合に用いることができる.
同じ@Expose注記は、An annotation that indicates this member should be exposed for JSON serialization or deserializationという意味です.Google APIのいくつかの言葉:
This annotation has no effect unless you build com.google.gson.Gson with a com.google.gson.GsonBuilder and invoke com.google.gson.GsonBuilder.excludeFieldsWithoutExposeAnnotation() method.
Here is an example of how this annotation is meant to be used:
 public class User {
   @Expose private String firstName;
   @Expose private String lastName;
   @Expose private String emailAddress;
   private String password;
 }
 
If you created Gson with new Gson(), the toJson() and fromJson() methods will use the password field along-with firstName, lastName, and emailAddress for serialization and deserialization. However, if you created Gson with Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() then the toJson() and fromJson() methods of Gson will exclude the password field. This is because the password field is not marked with the @Expose annotation.
Note that another way to achieve the same effect would have been to just mark the password field as transient, and Gson would have excluded it even with default settings. The @Expose annotation is useful in a style of programming where you want to explicitly specify all fields that should get considered for serialization or deserialization.