码迷,mamicode.com
首页 > Web开发 > 详细

json数据的拼接与解析

时间:2017-07-08 10:06:03      阅读:369      评论:0      收藏:0      [点我收藏+]

标签:引入   pen   parse   func   date   store   对象   path   repos   

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数据的拼接与解析

标签:引入   pen   parse   func   date   store   对象   path   repos   

原文地址:http://www.cnblogs.com/lixiang1993/p/7135757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!