1.新建实体类(其中字段信息根据自己要存储的内容添加):
public class JsonCityIdBean {
private String stratCityId;
private String transferCityId;
private String endCityId;
public String getStratCityId() {
return stratCityId;
}
public void setStratCityId(String stratCityId) {
this.stratCityId = stratCityId;
}
public String getTransferCityId() {
return transferCityId;
}
public void setTransferCityId(String transferCityId) {
this.transferCityId = transferCityId;
}
public String getEndCityId() {
return endCityId;
}
public void setEndCityId(String endCityId) {
this.endCityId = endCityId;
}
}
2.新建list集合,并将要转换的值添加到list集合中:
private List<JsonCityIdBean> jsonList=new ArrayList<>(); //新建的list集合
//实例化实体类,向实体类中添加自己需要转换的值
JsonCityIdBean jsonCityIdBean=new JsonCityIdBean();
jsonCityIdBean.setStratCityId(String.valueOf(startCityId));
jsonCityIdBean.setTransferCityId(String.valueOf(transferCityId));
jsonCityIdBean.setEndCityId(String.valueOf(endCityId));
//将添加完信息的实体类对象赋给list集合
jsonList.add(jsonCityIdBean);
//通过Gson将list集合转换为json格式字符串
Gson gson=new Gson();
String string=gson.toJson(jsonList);
UtilLog.e("#:"+string);
输出结果:TAG: #:[{"endCityId":"420100","stratCityId":"370100","transferCityId":"350100"}]