首页 > 代码库 > json数据的拼接与解析

json数据的拼接与解析

json数据格式

 [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },

{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},

{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }]

一、前台js代码(数据存储与json拼接)

以OutStoDetail类为例

技术分享

var proDetail=[];//大的集合
obj.outstodeid=outstodeid;  //对象属性
obj.proname=proname;
obj.proprice=proprice;
obj.procount=procount;
obj.proamount=proamount;
obj.storagenum=storagenum;
obj.localnum=localnum;
proDetail.push(obj );   //对象放入集合

$("#btnSave").click(function(){
    var jsonStr="[";
    for(i=0;i<proDetail.length;i++){
        jsonStr+="{";
        jsonStr+="\"outstodeid\":\""+proDetail[i].outstodeid+"\",";
        jsonStr+="\"proname\":\""+proDetail[i].proname+"\",";
        jsonStr+="\"proprice\":\""+proDetail[i].proprice+"\",";
        jsonStr+="\"procount\":\""+proDetail[i].procount+"\",";
        jsonStr+="\"proamount\":\""+proDetail[i].proamount+"\",";
        jsonStr+="\"storagenum\":\""+proDetail[i].storagenum+"\",";
        jsonStr+="\"localnum\":\""+proDetail[i].localnum+"\"";
        jsonStr+="}";
        if(i!=proDetail.length-1) jsonStr+=",";
    }
    jsonStr+="]";
        $.ajax({
        type:"post",
        url:<%=basePath%>outStore/updateOrAdd.action?jsonStr=+jsonStr,
        success:function(data,status){}
    });
});

拼接json串时注意引号的拼接。

二、后台java代码(json数据解析)

1、在maven项目pom.xml中添加如下依赖

<!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20170516</version>
    </dependency>

或下载org.json的jar包

2、在controller中对json数据进行解析

引入包

import org.json.JSONArray;
import org.json.JSONObject;
List<OutStoDetail> outSDList=new ArrayList<OutStoDetail>();
JSONArray js = new JSONArray(jsonStr);
for (int i = 0; i < js.length(); i++) {
  JSONObject ob = js.getJSONObject(i);
  OutStoDetail outStoDetail=new OutStoDetail();
  //outStoDetail.setOutstodeid(Integer.parseInt((String) ob.get("outstodeid")));
  outStoDetail.setProname((String)ob.get("proname"));
  outStoDetail.setProprice(Float.parseFloat((String)ob.get("proprice")));
  outStoDetail.setProcount(Float.parseFloat((String)ob.get("procount")));
  outStoDetail.setProamount(Float.parseFloat((String)ob.get("proamount")));
  outStoDetail.setStoragenum((String)ob.get("storagenum"));
  outStoDetail.setLocalnum((String)ob.get("localnum"));
  outStoDetail.setOutstonum(outStor.getOutstonum());
  outSDList.add(outStoDetail);
}

获取到OutStoDetail类型的集合就可以使用了。

json数据的拼接与解析