首先讲一下原理,json和String类型的数据,用js或者jquery可以互相转换,因此java只要生成符合json语法的String就可以了
第一种:单个实体类转json
package domain;
public class Commodity {
private Integer id;
private String name;
private String img_path;
private String detail;
private Integer price;
private Integer inventory;
private boolean putaway;
private boolean exist;
private Integer seles_volume;
public Commodity() {
}
public Commodity(Integer id, String name, String img_path, String detail, Integer price, Integer inventory, boolean putaway, boolean exist, Integer seles_volume) {
this.id = id;
this.name = name;
this.img_path = img_path;
this.detail = detail;
this.price = price;
this.inventory = inventory;
this.putaway = putaway;
this.exist = exist;
this.seles_volume = seles_volume;
}
public Commodity getCommodity(){
return this;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImg_path() {
return img_path;
}
public void setImg_path(String img_path) {
this.img_path = img_path;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getInventory() {
return inventory;
}
public void setInventory(Integer inventory) {
this.inventory = inventory;
}
public boolean isPutaway() {
return putaway;
}
public void setPutaway(boolean putaway) {
this.putaway = putaway;
}
public boolean isExist() {
return exist;
}
public void setExist(boolean exist) {
this.exist = exist;
}
public Integer getSeles_volume() {
return seles_volume;
}
public void setSeles_volume(Integer seles_volume) {
this.seles_volume = seles_volume;
}
@Override
public String toString() {
return "{" +
"\"id\":" + id +
", \"name\":\"" + name + '\"' +
", \"img_path\":\"" + img_path + '\"' +
", \"detail\":\"" + detail + '\"' +
", \"price\":" + price +
", \"inventory\":" + inventory +
", \"putaway\":" + putaway +
", \"exist\":" + exist +
", \"seles_volume\":" + seles_volume +
"}";
}
}
注意此处的toString方法,自动生成以后,需要稍作改变,如下图所示
自动生成代码
修改以后的代码
这样就可以通过调用toString方法获取单个实体类的json数据
第二种:实体类集合转json
先写个实体类的扩展类
package domain;
import java.util.List;
public class CommodityExt {
public CommodityExt() {
}
public CommodityExt(List<Commodity> commoditiys) {
this.commoditiys = commoditiys;
}
private List<Commodity> commoditiys;
public List<Commodity> getCommoditiys() {
return commoditiys;
}
public void setCommoditiys(List<Commodity> commoditiys) {
this.commoditiys = commoditiys;
}
public String listToString(List<Commodity> commoditiys){
String list = "[";
for (int i = 0;i<commoditiys.size();i++){
list+=commoditiys.get(i);
if (i< commoditiys.size()-1){
list+=",";
}
}
list += "]";
return list;
}
}
这里需要注意,for循环前后加的值中括号[]而不是大括号{},且最后一个对象不要加 逗号 ,
这样就完成类,然后用jquery方法就可以将字符串转化为json
var j = JSON.parse(data);