懶蟲蟲~
已于 2022-05-11 17:23:52 修改
5205
收藏 7
分類專欄: Java 文章標(biāo)簽: json java
版權(quán)
Java
專欄收錄該內(nèi)容
42 篇文章2 訂閱
訂閱專欄
一:三種JSON格式
基本類型
{
"student": "張三",
"age": 18,
"sex": true
}
數(shù)組類型
[
{
"student": "張三",
"age": 18,
"sex": true
},
{
"student": "李四",
"age": 19,
"sex": false
}
]
對(duì)象嵌套
{
"student": "張三豐",
"school": {
"class":"7班",
"floor": "5層"
},
"students": [
{
"student": "張三",
"age": 18,
"sex": true
},
{
"student": "李四",
"age": 19,
"sex": false
}
]
}
二:利用alibaba.fastjson解析JSONObject、JSONArray
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字符串-簡(jiǎn)單對(duì)象型
final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
// json字符串-數(shù)組類型
final String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
testJSONStrToJSONArray1(JSON_ARRAY_STR);
testJSONStrToJSONObject(JSON_OBJ_STR);
}
/**
* json字符串-數(shù)組類型與JSONArray之間的轉(zhuǎn)換
*/
public static void testJSONStrToJSONArray1(String JSON_ARRAY_STR) {
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
// JSONArray jsonArray1 =JSONArray.parseArray(JSON_ARRAY_STR);//因?yàn)镴SONArray繼承了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字符串-簡(jiǎn)單對(duì)象型與JSONObject之間的轉(zhuǎn)換
*/
public static void testJSONStrToJSONObject(String JSON_OBJ_STR) {
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
//JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); //因?yàn)镴SONObject繼承了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 {
//記得轉(zhuǎn)義
String jsonStr="{\"studentName\":\"zhangsanfeng\",\"age\":18,\"school\":\"武當(dāng)山大學(xué)\"}";
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);
}
}
解析如下形式j(luò)son數(shù)組
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數(shù)組后臺(tái)解析分組,比如按照OrderNum
數(shù)據(jù)庫(kù)中數(shù)據(jù)存儲(chǔ)如下:
原始數(shù)據(jù)類型如下:
[
{
ORDER_NUM=SD2520200522001,
WERKS_DN=2050,
POSNR=000010
},
{
ORDER_NUM=SD2520200610001,
WERKS_DN=2050,
POSNR=000010
},
{
ORDER_NUM=SD2520200610001,
WERKS_DN=2050,
POSNR=000010
}
]
比如同一個(gè)單號(hào),需要處理成如下類型json數(shù)據(jù)類型
{
"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();//從數(shù)據(jù)庫(kù)中查詢出數(shù)據(jù)
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進(jìn)行區(qū)分
if(!obj.containsKey(orderNum)) {//如果JSONObject不存在,則存按照<orderNum,List>形式存入JSONObject
List<Map<String,Object>> tempList = new ArrayList<>();//創(chuàng)建臨時(shí)tempList作為list存儲(chǔ)json數(shù)據(jù)
tempList.add(map);
obj.put(orderNum, tempList);
}else {//如果存在,則先取出放入臨時(shí)list,然后將當(dāng)前的map存入臨時(shí)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("倉(cāng)管員收貨自動(dòng)過賬提交BPM異常!", ex);
}
}
五:JS解析JSON對(duì)象
利用eval函數(shù)進(jìn)行轉(zhuǎn)換
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數(shù)組
6.1 解析方式1
拼接json數(shù)組,如{“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數(shù)組格式如下
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;//交貨項(xiàng)目
var MATNR = arraus[i].MATNR;//物料號(hào)
var ARKTX = arraus[i].ARKTX;//銷售訂單項(xiàng)目短文本
var MEINS = arraus[i].MEINS;//基本計(jì)量單位
var LGMNG = arraus[i].LGMNG;//以倉(cāng)庫(kù)保管單位級(jí)的實(shí)際交貨數(shù)量
var KBETR = arraus[i].KBETR;//價(jià)格
var WAERS = arraus[i].WAERS;//貨幣碼
var WBSTA = arraus[i].WBSTA;//貨物移動(dòng)狀態(tài)
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互相轉(zhuǎn)換
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轉(zhuǎn)換成JSONObject
返回值為bigDecimal值類型,存入double類型變量,result為Object。
這里需要將Object轉(zhuǎn)換成JSONObject類型,然后進(jìn)行解析。
"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 {
/**
* 外部服務(wù)商訂單ID
*/
String outOrderId;
/**
* 配送距離(單位:米)
*/
Double distance;
/**
* 實(shí)際運(yùn)費(fèi)(單位:元),運(yùn)費(fèi)減去優(yōu)惠券費(fèi)用
*/
Double fee;
/**
* 運(yùn)費(fèi)(單位:元)
*/
Double deliverFee;
/**
* 優(yōu)惠券費(fèi)用(單位:元)
*/
Double couponFee;
/**
* 小費(fèi)(單位:元)
*/
Double tips;
/**
* 保價(jià)費(fèi)(單位:元)
*/
Double insuranceFee;
}
1
//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); //轉(zhuǎn)換成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")
三、返回對(duì)象是JSONArray格式
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
文章知識(shí)點(diǎn)與官方知識(shí)檔案匹配,可進(jìn)一步學(xué)習(xí)相關(guān)知識(shí)
————————————————
聯(lián)系客服