1 开始使用
- https://github.com/google/gson
compile 'com.google.code.gson:gson:2.8.0'
2 基本使用
Gson gson = new Gson();
int anInt = gson.fromJson("111", int.class);
double aDouble = gson.fromJson("\"11.11\"", double.class);
boolean aBoolean = gson.fromJson("true", boolean.class);
String string = gson.fromJson("test", String.class);
String jsonNumber = gson.toJson(10);
String jsonBoolean = gson.toJson(false);
String jsonString = gson.toJson("str");
3 对象解析
TestBean testBean=new TestBean((byte)1,(short)2,3,4L,5F,6D,true,'d',"testStr");
String jsonTestBean = gson.toJson(testBean);
String jsonTest="{\"string\":\"testStr\",\"aByte\":1,\"aLong\":4,\"aDouble\":6.0,\"aFloat\":5.0,\"aChar\":\"d\",\"aShort\":2,\"anInt\":3,\"aBoolean\":true}\n";
TestBean testBeanBack=gson.fromJson(jsonTest,TestBean.class);
4 字符串数组
String jsonArray = "[\"Android\",\"Java\",\"C#\"]";
String[] strings = gson.fromJson(jsonArray, String[].class);
List<String> stringList = gson.fromJson(jsonArray, new TypeToken<List<String>>() {}.getType());
5 泛型数组
List<TestBean> tbList=new ArrayList<>();
for (int i = 0; i < 2; i++) {
tbList.add(new TestBean((byte)1,(short)2,3,4L,5F,6D,true,'d',"testStr_"+i));
}
String jsonTestBeanList = gson.toJson(tbList);
String jsonTestListStr="[{\"string\":\"testStr_0\",\"aByte\":1,\"aLong\":4,\"aDouble\":6.0,\"aFloat\":5.0,\"aChar\":\"d\",\"aShort\":2,\"anInt\":3,\"aBoolean\":true},{\"string\":\"testStr_1\",\"aByte\":1,\"aLong\":4,\"aDouble\":6.0,\"aFloat\":5.0,\"aChar\":\"d\",\"aShort\":2,\"anInt\":3,\"aBoolean\":true}]";
List<TestBean> tbL = gson.fromJson(jsonTestListStr,new TypeToken<List<TestBean>>() {}.getType());
6 过滤字段
private transient int anInt;
- 2 @Expose 暴露字段,就是在需要导出的字段上加@Expose 注解,配合GsonBuilder使用
@Expose 默认 deserialize = true,serialize = true
@Expose(deserialize = true,serialize = true)
@Expose(deserialize = true,serialize = false)
@Expose(deserialize = false,serialize = true)
@Expose(deserialize = false,serialize = false)
@Expose
private int anInt;
Gson gson4Expose = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
gson4Expose.toJson(obj);
7 指定字段名称
- value 指定属性名,以下方式 {“w”:10,“h”:20,“d”:30} 可以被解析到 width,height和depth字段中
@SerializedName("w")
private int width;
@SerializedName("h")
private int height;
@SerializedName(value = "d")
private int depth;
- alternate 指定备选属性名,当多种情况同时出时,以最后一个出现的值为准
@SerializedName(value = "esss",alternate = "es")
public String emailAddress;
@SerializedName(value = "emailAddress", alternate = {"email", "email_address"})
public String emailAddress;
8 通过 GsonBuilder 配置 Gson
Gson gson = new GsonBuilder()
.serializeNulls()
.setDateFormat("yyyy-MM-dd")
.disableInnerClassSerialization()
.generateNonExecutableJson()
.disableHtmlEscaping()
.setPrettyPrinting()
.create();
9 Gson处理泛型的问题
public static <T> T fromJson(String json,TypeToken<T> token) {
if (json == null || json.trim().length() <= 0) {
Log.d("BaseBeanXxx", "fromJson: json is error");
return null;
}
Type objectType = token.getType();
return new Gson().fromJson(json, objectType);
}
public static <T> T fromJson2(String json,Class clazz) {
Type objectType = dealParameterizedTypeInner(BasicBean.class,clazz);
return new Gson().fromJson(json, objectType);
}
private static ParameterizedType dealParameterizedTypeInner(final Class raw,
final Type... args) {
ParameterizedType parameterizedType= new ParameterizedType() {
public Type getRawType() {
return raw;
}
public Type[] getActualTypeArguments() {
return args;
}
public Type getOwnerType() {
return null;
}
};
return parameterizedType;
}
public static <T> T fromJson3(String json, final Class clazz) {
Type parameterizedType= new ParameterizedType() {
public Type getRawType() {
return BasicBean.class;
}
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
public Type getOwnerType() {
return null;
}
};
return new Gson().fromJson(json, parameterizedType);
}
参考文章
- 你真的会用Gson吗?Gson使用指南(一)http://www.jianshu.com/p/e740196225a4
- Gson全解析(上)-Gson基础 http://www.jianshu.com/p/fc5c9cdf3aab