Gson的简单使用
1.配置
Gson下载地址:http://repo1.maven.org/maven2/com/google/code/gson/gson/
下载好后直接添加至lib即可
或者:
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency>
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
2.使用
这里需要一个Bean类,只需要和你的json字段一一对应即可。
如:
public class CheckGoalBean { long goalID; String goalContent; int goalType; @Override public String toString() { return "CheckGoalBean{" + "goalID=" + goalID + ", goalContent='" + goalContent + '\'' + ", goalType=" + goalType + '}'; } public long getGoalID() { return goalID; } public void setGoalID(long goalID) { this.goalID = goalID; } public String getGoalContent() { return goalContent; } public void setGoalContent(String goalContent) { this.goalContent = goalContent; } public int getGoalType() { return goalType; } public void setGoalType(int goalType) { this.goalType = goalType; } }
2.1对象转Json和Json转对象
//对象转json字符串 CheckGoalBean checkGoalBean=new CheckGoalBean(); checkGoalBean.setGoalID(1); checkGoalBean.setGoalType(1); checkGoalBean.setGoalContent("专注30分钟"); Gson gson=new Gson(); String json=gson.toJson(checkGoalBean); System.out.println(json);
//json字符串转对象 String json="{\"goalID\":1,\"goalContent\":\"专注30分钟\",\"goalType\":1}"; Gson gson=new Gson(); //参数(json字符串,对应的Bean类型) CheckGoalBean checkGoalBean=gson.fromJson(json,CheckGoalBean.class); System.out.println(checkGoalBean);
2.2List与Json的互相转换
//List<Bean>转json数组 Gson gson=new Gson(); String json=gson.toJson(checkGoalBeans);//checkGoalBeans是List
//Json数组转List<Bean> Gson gson=new Gson(); List<CheckGoalBean> list=gson.fromJson(jsonArrayString,new TypeToken<List<CheckGoalBean>>() {}.getType());