javascript
用字符串表达式访问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)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在WP-Config中设置WordP
- 下一篇: js中 json详解