2017年7月7日 见Gson 的@Expose 注解 和 @SerializedName 注解 查阅资料后 记录:
@Expost注解的作用:区分实体中不想被序列化的属性,包含俩个属性-deserialize(反序列化) 和 serialize(序列化) 默认true
使用new GsonBuilder().excludeFiedlsWithoutExpostAnnotaion().create();创建Gson对象,没有@Wxpose注释的属性讲不会被序列化.
@SerializedName 注解的作用:定义属性序列化后的名称;
下面是代码案例:
采用Gson studio 需添加依赖: (最好为版本较新的)
compile 'com.google.code.gson:gson:2.6.2'
package ....;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
/**
* Created by john on 2017/7/7.
*/
public class User implements Serializable {
private Long id;
@Expose
private int age;
@Expose
@SerializedName("username")
private String name;
public User(Long id, int age, String name){
this.id = id;
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}package com.example.dyf.dyfdemo.gson;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* Created by john on 2017/7/7.
*/
public class GsonActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//
testGson();
}
private void testGson(){
//gson的@Expose注解和@SerializedName注解
User user = new User(1L, 17, "Jion");
//使用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
//创建Gson对象,没有@Expose注释的属性将不会被序列化
Gson g1 = new Gson();
//使用 new Gson();
System.out.println(g1.toJson(user));// {"age":17,"id":1,"username":"Jion"}
//使用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Gson g2 = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(g2.toJson(user)); // {"age":17,"username":"Jion"}
}
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦