1 开始使用
compile 'com.google.code.gson:gson:2.8.0'
2 基本使用
//
Gson gson = new Gson();
// gson.fromJson
int anInt = gson.fromJson("111", int.class); // 111
double aDouble = gson.fromJson("\"11.11\"", double.class); // 11.11
boolean aBoolean = gson.fromJson("true", boolean.class); // true
String string = gson.fromJson("test", String.class); // test
// gson.toJson
String jsonNumber = gson.toJson(10); // 10
String jsonBoolean = gson.toJson(false); // false
String jsonString = gson.toJson("str"); // "str"
3 对象解析
TestBean testBean=new TestBean((byte)1,(short)2,3,4L,5F,6D,true,'d',"testStr");
String jsonTestBean = gson.toJson(testBean);//{"string":"testStr","aByte":1,"aLong":4,"aDouble":6.0,"aFloat":5.0,"aChar":"d","aShort":2,"anInt":3,"aBoolean":true}
//
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);// gson.fromJson(String json, Class<T> classOfT)
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":"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}]
//
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()
//序列化null,默认是排除null值
.serializeNulls()
// 设置日期时间格式,另有2个重载方法
// 在序列化和反序化时均生效
.setDateFormat("yyyy-MM-dd")
// 禁此序列化内部类InnerClass,嵌套类NestedClass不影响
.disableInnerClassSerialization()
//生成不可执行的Json(多了 )]}' 这4个字符)
.generateNonExecutableJson()
//禁止转义html标签
.disableHtmlEscaping()
//格式化输出
.setPrettyPrinting()
.create();
9 Gson处理泛型的问题
/**
* 用法
* TypeToken<BaseBean<OthersBean>> typeToken=new TypeToken<BaseBean<OthersBean>>(){};
* BaseBean<OthersBean> baseBean=BaseBean.fromJsonOne(body,typeToken);
* @param json
* @param token
* @param <T>
* @return
*/
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);
}
/**
* 用法
* BaseBean.fromJson(result,OthersBean.class);
* @param json
* @param clazz
* @param <T>
* @return
*/
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;
}
/**
* 用法
* BaseBean.fromJson(result,OthersBean.class);
* @param json
* @param clazz
* @param <T>
* @return
*
* 和2相同
*/
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);
}
参考文章
网友评论