Java、JS解析JSON对象、JSON数组

一:三种JSON格式

基本类型

{
    "student": "张三",
    "age": 18,
    "sex": true
}

数组类型

[
    {
        "student": "张三",
        "age": 18,
        "sex": true
    },
    {
        "student": "李四",
        "age": 19,
        "sex": false
    }
]

对象嵌套

{
    "student": "张三丰",
    "school": {
    "class":"7班",
    "floor": "5层"
	},
	"students": [
        {
            "student": "张三",
            "age": 18,
            "sex": true
        },
        {
            "student": "李四",
            "age": 19,
            "sex": false
        }
    ]
}

二:利用alibaba.fastjson解析JSONObject、JSONArray

Java、JS解析JSON对象、JSON数组_第1张图片

package com.test1;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestJsonArray {
	public static void main(String[] args) {
		// json字符串-简单对象型
		final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
		// json字符串-数组类型
		final String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";

		testJSONStrToJSONArray1(JSON_ARRAY_STR);
		testJSONStrToJSONObject(JSON_OBJ_STR);
	}

	/**
	 * json字符串-数组类型与JSONArray之间的转换
	 */
	public static void testJSONStrToJSONArray1(String JSON_ARRAY_STR) {

		JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
		// JSONArray jsonArray1 =JSONArray.parseArray(JSON_ARRAY_STR);//因为JSONArray继承了JSON,所以这样也是可以的
		// 遍历方式1
		int size = jsonArray.size();
		for (int i = 0; i < size; i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			System.out.println(jsonObject.getString("studentName") + ":" + jsonObject.getInteger("studentAge"));
		}

		// 遍历方式2
		for (Object obj : jsonArray) {
			JSONObject jsonObject = (JSONObject) obj;
			System.out.println(jsonObject.getString("studentName") + ":" + jsonObject.getInteger("studentAge"));
		}
	}

	/**
	 * json字符串-简单对象型与JSONObject之间的转换
	 */
	public static void testJSONStrToJSONObject(String JSON_OBJ_STR) {
		
		 JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
		 //JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); //因为JSONObject继承了JSON,所以这样也是可以的
		 System.out.println(jsonObject.getString("studentName") + ":" + jsonObject.getInteger("studentAge"));
    }
}

三:利用json.JSONObject解析JSONObject

package com.test1;
import org.json.JSONException;
import org.json.JSONObject;
public class TestJsonObject {
	 public static void main(String[] args) throws JSONException {
	        //记得转义
	        String jsonStr="{\"studentName\":\"zhangsanfeng\",\"age\":18,\"school\":\"武当山大学\"}";
	        JSONObject jsonObj = new JSONObject(jsonStr);
	        int age = jsonObj.getInt("age");
	        String school = jsonObj.optString("school");
	        String studentName= (String) jsonObj.get("studentName");
	        System.out.println(age);
	        System.out.println(school);
	        System.out.println(studentName);
	    }
}

解析如下形式json数组
Java、JS解析JSON对象、JSON数组_第2张图片

	 		JSONObject json = new JSONObject(data);
			JSONArray rows = json.optJSONArray("IT_QUERY");
			for (int i = 0; i < rows.length(); i++) {
				JSONObject row = rows.optJSONObject(i);
				//打印出WERKS字段值
				System.out.println(row.optString("WERKS"));
			}

四:将json数组后台解析分组,比如按照OrderNum

数据库中数据存储如下:
在这里插入图片描述
原始数据类型如下:

[
    {
        ORDER_NUM=SD2520200522001,
        WERKS_DN=2050,
        POSNR=000010
    },
    {
        ORDER_NUM=SD2520200610001,
        WERKS_DN=2050,
        POSNR=000010
    },
    {
        ORDER_NUM=SD2520200610001,
        WERKS_DN=2050,
        POSNR=000010
    }
]

比如同一个单号,需要处理成如下类型json数据类型

{
    "SD2520200611004":[
        {
            "ORDER_NUM":"SD2520200611004",
            "WERKS_DN":"2050",
            "POSNR":"000010"
        }],
    "SD2520200610001":[
        {
            "ORDER_NUM":"SD2520200610001",
            "WERKS_DN":"2050",
            "POSNR":"000010"
        },
        {
            "ORDER_NUM":"SD2520200610001",
            "WERKS_DN":"2050",
            "POSNR":"000010"
        }],
    "SD2520200522001":[
        {
            "ORDER_NUM":"SD2520200522001",
            "WERKS_DN":"2050",
            "POSNR":"000010"
        }]
}

java代码如下:

	public void run() {
		// TODO Auto-generated method stub
		SD25TaskService sd25TaskService = applicationContext.getBean(SD25TaskService.class);
		try {
			List list = sd25TaskService.getData();//从数据库中查询出数据
			JSONObject obj = new JSONObject();
			for (int i = 0; i < list.size(); i++) {
				Map<String,Object> map = (Map<String, Object>) list.get(i);//遍历获取字段集合
				String orderNum = map.get("ORDER_NUM").toString();//按照ORDER_NUM进行区分
				if(!obj.containsKey(orderNum)) {//如果JSONObject不存在,则存按照形式存入JSONObject
					List<Map<String,Object>> tempList = new ArrayList<>();//创建临时tempList作为list存储json数据
					tempList.add(map);
					obj.put(orderNum, tempList);
				}else {//如果存在,则先取出放入临时list,然后将当前的map存入临时tempList
					List<Map<String,Object>> tempList = (List<Map<String, Object>>) obj.get(orderNum);
					tempList.add(map);
				}
			}
			System.out.println(obj);
			
		} catch (Exception ex) {
			LOG.error("仓管员收货自动过账提交BPM异常!", ex);
		}
	}

五:JS解析JSON对象

利用eval函数进行转换

var data= {
	"name": "zhangsanfeng",
	"age": 118,
	"address": "beijing"
};

var json = eval('(' + data+ ')');
console.info(json.name);
console.info(json.age);
console.info(json.address);

六:解析JSON数组

6.1 解析方式1
拼接json数组,如{“IT_ITEM”:[{“VBELN”:“0080001496”}]}

  var arry = [];
  var jsonArray = {};
  jsonArray.VBELN = "0080001496";
  arry.push(jsonArray);
  
  var inputTables = {};
  inputTables.IT_ITEM = arry;
  console.info(JSON.stringify(inputTables))

json数组格式如下
var data = “{“ET_INFO”:[{“VBELN”:“80001496”,“KBETR”:3.00,“POSNR”:“000010”,“ARKTX”:“受话器SDRP0615PJ02-04-056”,“WAERS”:“RMB”,“MEINS”:“PCS”,“LGMNG”:20.000,“WBSTA”:“A”,“MATNR”:“000000001400009338”,“NAME1”:“AMAZON”}]}”;

{
	"ET_INFO": [{
		"VBELN": "8000149",
		"KBETR": 3.00,
		"POSNR": "000010",
		"ARKTX": "受话器SD",
		"WAERS": "RMB",
		"MEINS": "PCS",
		"LGMNG": 20.0,
		"WBSTA": "A",
		"MATNR": "00000000140",
		"NAME1": "AMA"
	}]
}
 var arrays = $.parseJSON(data.data).ET_INFO;
 for(var i=0 ;i<arrays.length;i++){
   var POSNR = arraus[i].POSNR;//交货项目
   var MATNR = arraus[i].MATNR;//物料号
   var ARKTX = arraus[i].ARKTX;//销售订单项目短文本
   var MEINS = arraus[i].MEINS;//基本计量单位
   var LGMNG = arraus[i].LGMNG;//以仓库保管单位级的实际交货数量
   var KBETR = arraus[i].KBETR;//价格
   var WAERS = arraus[i].WAERS;//货币码
   var WBSTA = arraus[i].WBSTA;//货物移动状态
   var NAME1 = arraus[i].NAME1;//名称
 }

6.2 解析方式2

var array = [{
			"name": "zhangsanfeng",
			"age": 118,
			"address": "beijing"
		}, {
			"name": "lisiguang",
			"age": 119,
			"address": "shanghai"
		}, {
			"name": "wangwuha",
			"age": 117,
			"address": "hangzhou"
		}];
for (var i in array ) {
    console.info(array[i].name);
    console.info(array[i].age);
    console.info(array[i].address);
}

七:JSON与Map互相转换

package com.gzsolartech.bpmportal.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.directwebremoting.json.types.JsonObject;
import org.json.JSONArray;
import org.json.JSONObject;

public class JsonMapUtil {
	public static Map convertJsonObjectToMap(JSONObject json){
		Map returnMap = new HashMap();
		Iterator<String> iterator = json.keys();
		while(iterator.hasNext()){
			String key = iterator.next();
			returnMap.put(key, json.opt(key));
		}
		return returnMap;
	}
	public static JSONObject convertMapToJsonObject(Map<String,Object> map){
		JSONObject json = new JSONObject();
		Set<String> set = map.keySet();
		Iterator<String> iterator = set.iterator();
		while(iterator.hasNext()){
			String key = iterator.next();
			json.put(key, map.get(key));
		}
		return json;
	}
	public static List<Map> convertJsonArrayToMap(JSONArray jsonArr){
		Map returnMap = new HashMap();
		List<Map> list = new ArrayList<>();
		for(int i=0;i<jsonArr.length();i++){
			JSONObject json = jsonArr.optJSONObject(i);
			Map map = convertJsonObjectToMap(json);
			list.add(map);
		}
		return list;
	}
	
}

八:Object转换成JSONObject

返回值为bigDecimal值类型,存入double类型变量,result为Object。
这里需要将Object转换成JSONObject类型,然后进行解析。

    "status": "success",
    "code": 0,
    "msg": "成功",
    "result": {
        "insuranceFee": 0.0,
        "distance": 33594.0,
        "fee": 264.0,
        "deliverFee": 264.0, 
        "tips": 218.1  
    }

O2oOrderResp

public class O2oOrderResp {
    /**
     * 外部服务商订单ID
     */
    String outOrderId;
    /**
     * 配送距离(单位:米)
     */
    Double distance;
    /**
     * 实际运费(单位:元),运费减去优惠券费用
     */
    Double fee;
    /**
     * 运费(单位:元)
     */
    Double deliverFee;
    /**
     * 优惠券费用(单位:元)
     */
    Double couponFee;
    /**
     * 小费(单位:元)
     */
    Double tips;
    /**
     * 保价费(单位:元)
     */
    Double insuranceFee;
}    
//o2oOrderResp = JSONObject.parseObject(JSON.toJSONString(dadaApiResponse.getResult()), O2oOrderResp.class);
//JSONObject result = dadaApiResponse.getResult();
JSONObject result = (JSONObject) JSON.toJSON(dadaApiResponse.getResult());
o2oOrderResp.setDeliverFee(result.getDouble("deliveryFee"));
o2oOrderResp.setInsuranceFee(result.getDouble("insuranceFee"));               o2oOrderResp.setFee(result.getDouble("fee"));             o2oOrderResp.setTips(result.getDouble("tips"));              o2oOrderResp.setDistance(result.getDouble("distance"));               o2oOrderResp.setCouponFee(result.getDouble("couponFee"));

其他格式举例

一.result格式:

{
    "success":"true",
    "returnAddress":"123"
}

JSONObject jsonObject=JSON.parseObject(result);      //转换成object
 
jsonObject.getString("returnAddress")    //获取object中returnAddress字段;                                                       

二.result格式:

{
    "success":"true",
    "data":{
        "shop_uid":"123"
    }
}

JSONObject shop_user =JSON.parseObject(result);
JSON.parseObject(shop_user.getString("data")).getString("shop_uid")

三、返回对象是JSONArray格式
Java、JS解析JSON对象、JSON数组_第3张图片

List<CancelReasonDTO> cancelReasonDTOList = new ArrayList<>();
JSONArray array = (JSONArray) dadaApiResponse.getResult();
          array.stream().forEach(
                    i ->{
                        JSONObject object = JSONArray.parseObject(i.toString());
                        CancelReasonDTO cancelReasonDTO = new CancelReasonDTO();
                        cancelReasonDTO.setCancelCode((Integer) object.get("id"));
                        cancelReasonDTO.setCancelName((String) object.get("reason"));
                        cancelReasonDTOList.add(cancelReasonDTO);
                    }
            );

参考文章
https://blog.csdn.net/dirft_din/article/details/108325419
https://www.yiibai.com/html/json/2013/0906249.html

你可能感兴趣的:(Java,json,java)