1. 程式人生 > >奇淫巧技之 Gson

奇淫巧技之 Gson

SerializedName 註解

最近Gson用的比較多,用的時候一直有一個疑問,難道本地的實體類的屬性名一定要和Json的鍵一一對應嗎?

註解了@SerializedName的欄位會被序列化到JSON中,輸出的JSON格式中的名字即為註解時給定的名字。 http://suoyihen.iteye.com/blog/1355936‘>google的@SerializedName和@Expose註解

說白了,這個註解就是考慮到返回的Json資料的欄位可能並不是我們想要的欄位而建立的,使用這個註解,我們的程式碼就可以這樣寫:

Json

{
  "person_name": "wangdachui"
, "person_age": 20, "tall": "176", "person_sex": "male" }

實體類屬性:

@SerializedName("person_name") String name;
@SerializedName("person_age") String age;
@SerializedName("person_sex") String sex;
String tall;

SerializedName註解的原始碼:

/**
 * An annotation that indicates this member should be serialized to JSON with
 * the provided name value as its field name.
 *
 * <p>This annotation will override any {@link com.google.gson.FieldNamingPolicy}, including
 * the default field naming policy, that may have been set on the {@link com.google.gson.Gson}
 * instance.  A different naming policy can set using the {@code GsonBuilder} class.  See
 * {@link com.google.gson.GsonBuilder#setFieldNamingPolicy(com.google.gson.FieldNamingPolicy)}
 * for more information.</p>
 *
 * <p>Here is an example of how this annotation is meant to be used:</p>
 * <pre>
 * public class SomeClassWithFields {
 *   &#64SerializedName("name") private final String someField;
 *   private final String someOtherField;
 *
 *   public SomeClassWithFields(String a, String b) {
 *     this.someField = a;
 *     this.someOtherField = b;
 *   }
 * }
 * </pre>
 *
 * <p>The following shows the output that is generated when serializing an instance of the
 * above example class:</p>
 * <pre>
 * SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
 * Gson gson = new Gson();
 * String jsonRepresentation = gson.toJson(objectToSerialize);
 * System.out.println(jsonRepresentation);
 *
 * ===== OUTPUT =====
 * {"name":"a","someOtherField":"b"}
 * </pre>
 *
 * <p>NOTE: The value you specify in this annotation must be a valid JSON field name.</p>
 *
 * @see
com.google.gson.FieldNamingPolicy * * @author Inderjeet Singh * @author Joel Leitch */
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface SerializedName { /** * @return the desired name of the field when it is serialized */ String value(); }