概述: Gson就是把class类对象中的数据使用json的格式输出。
① 代码部分:
static class Response<T> {
private T data;
private int code;
private String message;
public Response(T data, int code, String message) {
this.data = data;
this.code = code;
this.message = message;
}
@Override
public String toString() {
return "Response{" +
"data=" + data +
", code=" + code +
", message='" + message + '\'' +
'}';
}
}
static class Data {
private String result;
public Data(String result) {
this.result = result;
}
@Override
public String toString() {
return "Data{" +
"result='" + result + '\'' +
'}';
}
}
②main方法中使用Gson把Response类进行json格式输出
public static void main(String[] args) {
Data data = new Data("Gson data");
Response response = new Response(data, 001, "receive response from server");
//创建Gson对象:gson
Gson gson = new Gson();
//把Response对象进行序列化
final String json = gson.toJson(response);
//输出json数据
System.out.println(json);
}
③运行结果:
④ 因为使用到了Gson库,所以要在build.gradle文件中引入Gson库。
implementation ‘com.google.code.gson:gson:2.6.2’