gson的基本用法:
反序列化:将json转换为类
Gson gson = new Gson();
Data i = gson.fromJson("100", Data.class); <pre class="html" name="code"> List<对象类>list=gson.fromJson(json,new TypeToken<List<Food>>() {}.getType()); <span style="color:#33cc00;">//将json转换为集合</span>
<pre class="hljs java"><code class="java">String[] strings = gson.fromJson(jsonArray, String[].class);</code> <span style="color:#33cc00;">//将json转换为数组</span>
序列化:将类转换为json
Gson gson = new Gson();
String jsonNumber = gson.toJson(100); // 100
@SerializedNamer注解:将JSON字段的值解析到emailAddress中
//设置单个字段名
@SerializedName("email_address")
public String emailAddress;
<span style="color:#33cc00;"> //当alternate数组中出现任意一个时,都可以得到正确结构
</span>@SerializedName(value = "emailAddress", alternate = {"email", "email_address"})
public String emailAddress;
泛型:
直接看例子
public class UserResponse {
public int code;
public String message;
public User data;
}
public class UserResponse {
public int code;
public String message;
public Client data;
}
<pre class="html" name="code">public class Result<T> {
public int code;
public String message;
public T data;
}
//请求数据
<pre class="hljs php"><code class="php">Type userListType = <span class="hljs-keyword">new</span> TypeToken<Result<<span class="hljs-keyword">List</span><User>>>(){}.getType();
Result<<span class="hljs-keyword">List</span><User>> userListResult = gson.fromJson(json,userListType);
<span class="hljs-keyword">List</span><User> users = userListResult.data;</code>
TypeAdapter:接管序列化和反序列化过程
自定义gson解析的过程,并且会大大提高性能
Gson gson=new GsonBuilder().registerTypeAdapter(Tb.class, new TypeAdapter<Tb>() {
@Override
public void write(JsonWriter jsonWriter, Tb tb) throws IOException { <span style="color:#33cc00;">//将对象转为字符串
</span> jsonWriter.beginObject();
jsonWriter.name("name").value(tb.name);
jsonWriter.name("age").value(tb.age);
jsonWriter.endObject();
}
@Override
public Tb read(JsonReader jsonReader) throws IOException { <span style="color:#33cc00;"> //将字符串转为类
</span> Tb user = new Tb();
jsonReader.beginObject();
while (jsonReader.hasNext()) {
switch (jsonReader.nextName()) {
case "name":
user.name = jsonReader.nextString();
break;
case "age":
user.age = jsonReader.nextInt();
break;
}
}
jsonReader.endObject();
return user;
}
}).create();
Log.e("dddd",gson.toJson(new Tb("哈哈",20)));
注册了 TypeAdapter
之后,@SerializedName
、FieldNamingStrategy
、Since
、Until
、Expos都
失去了效果,只会调用我们实现的UserTypeAdapter.write(JsonWriter, User)
方法