我是 JSON 新手。我在 jsp 中有一个动态 html 表,可以在单击按钮时添加行。我能够在 servlet 中接收 JSON 字符串,但无法对其进行解码。我想分割字符串并将数据插入数据库。我的 JSON 字符串如下所示:
[{"srno":"1","itemcode":"4545","type":"45454","subtype":"54","sku":"45","invqty":"54","invprice":"54","折扣":"5","总计":"45"},{"srno":"2","itemcode":"44","type":"54","子类型":"45","sku":"45","invqty":"4","invprice":"54","折扣":"54","总计":"5"}]
最佳答案
我相信这是使用 jackson 解析器的一种可能的解决方案。
如果你想使用这个库,你必须为该类创建自己的类并反序列化它。
你的类(class)可能是..
class MyJsonClass
{
private String srno;
private String itemcode;
private String type;
private String subtype;
private String sku;
private String invqty;
private String invprice;
private String discount;
private String total;
public String getSrno(){ return srno;}
public void setSrno(String srno){ this.srno = srno;}
public String getItemcode(){ return itemcode;}
public void setItemcode(String itemcode){ this.itemcode = itemcode;}
public String getType(){ return type;}
public void setType(String type){ this.type = type;}
public String getSubtype(){ return subtype;}
public void setSku(String sku){ this.sku = sku;}
public String getSku(){ return sku;}
public void setSubtype(String subtype){ this.subtype = subtype;}
public String getInvqty(){ return invqty;}
public void setInvqty(String invqty){ this.invqty = invqty;}
public String getInvprice(){ return invprice;}
public void setInvprice(String invprice){ this.invprice = invprice;}
public String getDiscount(){ return discount;}
public void setDiscount(String discount){ this.discount = discount;}
public String getTotal(){ return total;}
public void setTotal(String total){ this.total = total;}
@Override
public String toString()
{
StringBuffer stbuf = new StringBuffer();
stbuf.append("srno : ").append(srno);
stbuf.append(" itemcode : ").append(itemcode);
stbuf.append(" type : ").append(type);
stbuf.append(" subtype : ").append(subtype);
stbuf.append(" sku : ").append(sku);
stbuf.append(" invqty : ").append(invqty);
stbuf.append(" invprice : ").append(invprice);
stbuf.append(" discount : ").append(discount);
stbuf.append(" total : ").append(total);
return stbuf.toString();
}
}
然后,主入口代码可能如下所示。
public class MyBizParser {
public static void main(String[] args)
{
String yourJson =
"["
+ "{\"srno\":\"1\",\"itemcode\":\"4545\",\"type\":\"45454\",\"subtype\":\"54\",\"sku\":\"45\",\"invqty\":\"54\",\"invprice\":\"54\",\"discount\":\"5\",\"total\":\"45\"},"
+ "{\"srno\":\"2\",\"itemcode\":\"44\",\"type\":\"54\",\"subtype\":\"45\",\"sku\":\"45\",\"invqty\":\"4\",\"invprice\":\"54\",\"discount\":\"54\",\"total\":\"5\"}"
+ "]";
parsingIt(yourJson);
}
private static void parsingIt(String yourJson) {
ObjectMapper objMapper = new ObjectMapper();
try {
MyJsonClass[] myObjects = objMapper.readValue(yourJson, MyJsonClass[].class);
for(int i = 0; i < myObjects.length; i++)
System.out.println(myObjects[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我希望这是你想要的..
关于java - Java Servlet中Json字符串解析并插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45726689/