首先講一下原理,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);