Gson(1)简单使用
1.官方资料
官网: http://groups.google.com/group/google-gson
代码: https://github.com/google/gson
jar包下载: http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.3.1%7Cjar
2.导入
在as工程属性中找最新的gson库,或者直接在module的build.gradle中引入gson库.
1 dependencies { 2 implementation fileTree(include: ['*.jar'], dir: 'libs') 3 implementation 'com.android.support:appcompat-v7:27.1.1' 4 implementation 'com.android.support.constraint:constraint-layout:1.1.2' 5 //... 6 implementation 'com.google.code.gson:gson:2.8.5' 7 }
3.对象转json
3.1准备对象
1 public class Person { 2 3 private String name; 4 private int age; 5 6 /** 7 * @return the name 8 */ 9 public String getName() { 10 return name; 11 } 12 13 /** 14 * @param name the name to set 15 */ 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 /** 21 * @return the age 22 */ 23 public int getAge() { 24 return age; 25 } 26 27 /** 28 * @param age the age to set 29 */ 30 public void setAge(int age) { 31 this.age = age; 32 } 33 34 @Override 35 public String toString() 36 { 37 return name + ":" +age; 38 } 39 }
实体很简单,两个字段,当然实体中的字段也可以是数组、List、Set等类型的。
3.2 生成Json字符串
1 //生成Json字符串 2 3 Gson gson = new Gson(); 4 List<Person> persons = new ArrayList<Person>(); 5 for (int i = 0; i < 10; i++) { 6 Person p = new Person(); 7 p.setName("name" + i); 8 p.setAge(i * 5); 9 persons.add(p); 10 } 11 String json = gson.toJson(persons);
上面的代码重点是Gson对象,它提供了toJson()方法将对象转换成Json字符串,可以这个json串写到文件中.上面代码的str对象值为:
[{"name":"name0","age":0},{"name":"name1","age":5},{"name":"name2","age":10},{"name":"name3","age":15}, {"name":"name4","age":20},{"name":"name5","age":25},{"name":"name6","age":30},{"name":"name7","age":35}, {"name":"name8","age":40},{"name":"name9","age":45}]
3.3 对象转json的系列函数
- String toJson(Object src, Type typeOfSrc)
- String toJson(Object src)
- JsonElement toJsonTree(Object src, Type typeOfSrc)
- JsonElement toJsonTree(Object src)
4.json转对象
Gson提供了fromJson()方法来实现从Json相关对象到java实体的方法。
在日常应用中,通常转成单一实体对象和转换成对象列表或者其他结构。
4.1反序列化一个对象
当返回的是简单对象(只一个对象)时用gson.fromJson(string,xx.class); //提供两个参数,分别是json字符串以及需要转换对象的类型
比如json字符串为:
[{"name":"name0","age":0}]
代码:
Person person = gson.fromJson(str, Person.class);
4.2 反序列成列表
当返回的是复杂对象,要用AVA泛型时,如有个集合(0-n)要用gson.fromJson(string,new TypeToken<XXX>(){}.getType());
代码:
1 List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType()); 2 for(int i = 0; i < ps.size() ; i++) 3 { 4 Person p = ps.get(i); 5 System.out.println(p.toString()); 6 }
上面的代码使用了TypeToken,它是gson提供的数据类型转换器,可以支持各种数据集合类型转换。
5. Gson处理 null
默认情况下,gson不处理null,处理方法如下:
5.1 定义 null 处理类
1 class StringConverter : JsonSerializer<String?>, 2 JsonDeserializer<String?> { 3 override fun serialize( 4 src: String?, typeOfSrc: Type?, 5 context: JsonSerializationContext? 6 ): JsonElement { 7 return if (src == null) { 8 JsonPrimitive("") 9 } else { 10 JsonPrimitive(src.toString()) 11 } 12 } 13 14 @Throws(JsonParseException::class) 15 override fun deserialize( 16 json: JsonElement, typeOfT: Type?, 17 context: JsonDeserializationContext? 18 ): String { 19 return json.asJsonPrimitive.asString 20 } 21 }
5.2 修改构造gson方式
1 fun parseDevices(array : JsonArray){ 2 val gb = GsonBuilder() 3 gb.registerTypeAdapter(String::class.java, StringConverter()) 4 val gson = gb.create() 5 for (je in array){ 6 val obj = je.asJsonObject 7 if(!obj.has("type")) continue 8 val type = obj.get("type").asInt 9 when(type){ 10 1 -> { 11 val ward = gson.fromJson(je,Wardship::class.java) 12 ... 13 } 14 15 //... 16 } 17 } 18 }
6.混淆
在 proguard-rules.pro 中:
1 #gson 2 -keepattributes Signature 3 4 # For using GSON @Expose annotation 5 -keepattributes *Annotation* 6 7 # Gson specific classes 8 -dontwarn sun.misc.** 9 #-keep class com.google.gson.stream.** { *; } 10 11 # Application classes that will be serialized/deserialized over Gson 12 13 -keep class com.xx.xx.Student { <fields>; } 14 -keep class com.xxx.xx.Daily{ <fields>; } 15 -keep class com.xxx.xxx.Persion { <fields>; } 16 #-keep class * extends com.xxx.xxx.Persion 17 18 # Prevent proguard from stripping interface information from TypeAdapter, TypeAdapterFactory, 19 # JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter) 20 -keep class * extends com.google.gson.TypeAdapter 21 -keep class * implements com.google.gson.TypeAdapterFactory 22 -keep class * implements com.google.gson.JsonSerializer 23 -keep class * implements com.google.gson.JsonDeserializer 24 25 # Prevent R8 from leaving Data object members always null 26 -keepclassmembers,allowobfuscation class * { 27 @com.google.gson.annotations.SerializedName <fields>; 28 }