Gson的用法例項
阿新 • • 發佈:2019-02-16
JSON字串解析成物件
- JSON字串
{
"mailNo": "12345678",
"orgCode": "315005"
}
- NameReq 程式碼
public class NameReq {
private String mailNo; //運單號
private String orgCode; //機構程式碼
public String getMailNo() {
return mailNo;
}
public void setMailNo(String mailNo) {
this.mailNo = mailNo;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
}
- 解析程式碼
NameReq nameReq = gson.fromJson(body, NameReq.class);
JSON字串解析成集合
- JSON字串
[{
"monthStartDay": "2018-04-01 00:00:00",
"monthEndDay": "2018-04-30 23:23:00"
}, {
"monthStartDay": "2018-05-01 00:00:00",
"monthEndDay": "2018-05-31 23:23:00"
}]
- DispatchParameter程式碼
public class DispatchParameter implements Serializable {
private String sitename;// 網點名稱
private String username;// 業務員名稱
private String monthStartDay;// 每月的開始日期
private String monthEndDay;// 每月的結束日期
public String getSitename() {
return sitename;
}
public void setSitename(String sitename) {
this.sitename = sitename;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMonthStartDay() {
return monthStartDay;
}
public void setMonthStartDay(String monthStartDay) {
this.monthStartDay = monthStartDay;
}
public String getMonthEndDay() {
return monthEndDay;
}
public void setMonthEndDay(String monthEndDay) {
this.monthEndDay = monthEndDay;
}
public DispatchParameter(String sitename, String username, String monthStartDay, String monthEndDay) {
super();
this.sitename = sitename;
this.username = username;
this.monthStartDay = monthStartDay;
this.monthEndDay = monthEndDay;
}
}
- 解析程式碼
Gson gson = new Gson();
List<DispatchParameter> reList = gson.fromJson(monthArray,
new TypeToken<List<DispatchParameter> >(){}.getType());
POM
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>