日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

用字符串表达式访问JSON数据(java,fastjson)

發布時間:2023/12/9 javascript 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用字符串表达式访问JSON数据(java,fastjson) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

//單元科技-www.ccell.com.cn 技術部,開源
//XML數據有XPATH 如"root/rows[@id=1]/name"
//在JS中JSON數據可以對象方式訪問
//java中怎么 用字符串表達式訪問JSON數據? 找了很久沒有找到,自己寫一個,以減小代碼量,讓程序可讀性變強
//用法:
//?? JSONObject json = JSON.parseObject("{a:1,b:{}}");
//?? JSONHelper.putByJPath(json, "b.abc", 123);
//?? System.out.println(json);
//?? System.out.println(JSONHelper.getByJPath(json, "b.abc", Integer.class));
//代碼:
package com.ccell.json;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


public class JSONHelper {

? public static? <T> Object getByJPath(JSONObject root, String jpath, Class<T> cls) {

??? if (root == null) {
????? return null;
??? }

??? if (jpath == null || "".equals(jpath)) {
?????
????? if (cls.equals(JSONObject.class)){
??????? return root;
????? }else{
??????? return null;
????? }
??? }
???
??? String[] names = jpath.split("\\.");
??? String key = names[0];

??? JSONObject jobj = null;
??? Object result = null;

??? if (key.matches("^.+(\\[\\d+\\])+$")) {

????? String[] tmps = key.replaceAll("\\]", "").split("\\[");

????? JSONArray jarray = root.getJSONArray(tmps[0]);

????? if (jarray != null) {
??????? for (int j = 1; j < tmps.length; j++) {

????????? int index = Integer.parseInt(tmps[j]);
????????? if (j == tmps.length - 1) {
??????????? if (names.length == 1) {
????????????? result = jarray.getObject(index, cls);
??????????? } else {
????????????? jobj = jarray.getJSONObject(index);
????????????? result = getByJPath(jobj, jpath.substring(key.length() + 1), cls);
??????????? }
????????? } else {
??????????? jarray = jarray.getJSONArray(index);
????????? }
??????? }
????? }

??? } else {

????? if (names.length == 1) {
??????? result = root.getObject(key, cls);
????? } else {
??????? jobj = root.getJSONObject(key);
??????? result = getByJPath(jobj, jpath.substring(key.length() + 1), cls);
????? }

??? }
???
??? return result;
???
? }

? public static void putByJPath(JSONObject root, String jpath, Object value) {

??? String key = jpath;
??? String parentpath = "";
??? int pos =? jpath.lastIndexOf(".");
??? if (pos >= 0){
????? key = jpath.substring(pos + 1);
????? parentpath = jpath.substring(0,pos );?????
??? }

??? JSONObject jobj = (JSONObject) getByJPath(root,parentpath,JSONObject.class);
??? jobj.put(key, value);
???
? }
?
}

轉載于:https://my.oschina.net/u/162811/blog/76501

總結

以上是生活随笔為你收集整理的用字符串表达式访问JSON数据(java,fastjson)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。