您的位置:首页 > 移动开发 > Android开发

奇淫巧技之 Gson

2016-06-17 03:44 405 查看

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 {
*   @SerializedName("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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  gson android json