奇淫巧技之 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(); }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories