json数据的拼接与解析

Posted bwlu---ed

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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=[];//大的集合
var obj=new Object();
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数据的拼接与解析的主要内容,如果未能解决你的问题,请参考以下文章

jsp页面中,如何使用jquery拼接json格式的数据

oracle如何把一行数据自动拼接成json格式数据

微信小程序json数据如何处理?

java与JSON

java解析和拼接json对象

片段中的 JSON 解析 [关闭]