栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 使用fastjson解析json中位置不固定的key

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 使用fastjson解析json中位置不固定的key

目录
      • 一、遇到的问题:
      • 二、使用递归遍历json查找key所在json对象
      • 三、测试:

一、遇到的问题:

要获取的key在json不确定的层级位置,例如下面三个JSON,其中的 blackAttach 分别出现在不同的地方。因为blackAttach这个key可能会出现在不同的JSON层级对象中,所以就很难解析。

json1.json如下:

{
	"datasource": [],
	"ui": {
		"id": "rootpanel",
		"type": "rootpanel",
		"blackAttach": "blackAttach_json1",
		"allowAttach": "txt",
		"children": [{
			"id": "flexpanel1",
			"type": "flexpanel",
			"events": {},
			"properties": {
				"title": "flexpanel"
			}
		}]
	},
	"version": "1",
	"title": "55",
	"pageType": "nav"
}

json2.json如下:

{
	"datasource": [],
	"ui": {
		"id": "rootpanel",
		"type": "rootpanel",
		"children": [{
			"children": [{
				"id": "panel1",
				"children": [{
					"id": "cardpanel1",
					"events": {},
					"properties": [{
							"name": "field2",
							"value": "$NULL"
						},
						{
							"blackAttach": "blackAttach_json2",
							"allowAttach": "txt"
						}
					],
					"children": []
				}]
			}]
		}]
	},
	"version": "1"
}

json3.json如下:

{
	"datasource": [],
	"ui": {
		"children": [{
			"id": "flexpanel1",
			"events": {},
			"properties": {
				"title": "flexpanel"
			},
			"children": [{
				"id": "panel1",
				"blackAttach": "blackAttach_json3",
				"allowAttach": "txt",
				"children": [{
					"id": "cardpanel1",
					"type": "cardpanel",
					"events": {},
					"properties": {
						"staticAttr": [{
							"name": "field1",
							"value": "$NULL"
						}]
					},
					"children": []
				}]
			}]
		}]
	}
}
二、使用递归遍历json查找key所在json对象

1.用到的fastjson依赖 maven如下:


    com.alibaba
    fastjson
    1.2.79


2.使用 JsonSearch 工具类来递归遍历整个 json 查找目标 key 所在的 json 返回

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;

public class JsonSearch {
    
    public static JSONObject findKey(JSONObject jsonObject, String searchKey) {
        JSONObject result = null;
        for (Map.Entry entry : jsonObject.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof JSONArray) {
                result = handleArray((JSONArray) value, searchKey);
            }
            if (value instanceof JSONObject) {
                result = handleJsonObject((JSONObject) value, searchKey);
            }
            if (result != null) {
                return result;
            }
        }
        return null;
    }

    
    public static JSONObject findKey(String jsonStr, String searchKey) {
        return findKey(JSONObject.parseObject(jsonStr), searchKey);
    }

    public static JSONObject handleArray(JSONArray array, String searchKey) {
        JSONObject result = null;
        for (int i = 0; i < array.size(); i++) {
            Object object = array.get(i);
            if (object instanceof JSONArray) {
                //递归查询
                result = handleArray((JSONArray) object, searchKey);
            }
            if (object instanceof JSONObject) {
                result = handleJsonObject((JSONObject) object, searchKey);
            }
            if (result != null) {
                return result;
            }
        }
        return null;
    }

    public static JSONObject handleJsonObject(JSONObject jsonObject, String searchKey) {
        JSONObject result = null;
        for (Map.Entry entry : jsonObject.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();
            if (value instanceof JSONArray) {
                result = handleArray((JSONArray) value, searchKey);
            }
            if (value instanceof JSONObject) {
                //递归查询
                result = handleJsonObject((JSONObject) value, searchKey);
            }
            if (result != null) {
                return result;
            }
            if (value instanceof String) {
                if (searchKey != null && searchKey.equals(key)) {
                    return jsonObject;
                }
            }
        }
        return null;
    }
}

三、测试:
public class MainServer {
    public static void main(String[] args) throws Exception {
         //获取json1文件内容
        String filePath1 = "F:\json\json1.json";
        String fileContent1 = new String(Files.readAllBytes(Paths.get(filePath1)), StandardCharsets.UTF_8);
        //json字符串中查找blackAttach所在的json对象返回
        JSONObject jsonObject1 = JsonSearch.findKey(fileContent1, "blackAttach");
        System.out.println("json1中包含blackAttach的JSON:" + jsonObject1);
        System.out.println("json1中的blackAttach:" + jsonObject1.getString("blackAttach"));
        System.out.println();

        //获取json2文件内容
        String filePath2 = "F:\json\json2.json";
        String fileContent2 = new String(Files.readAllBytes(Paths.get(filePath2)), StandardCharsets.UTF_8);
        //json字符串中查找blackAttach所在的json对象返回
        JSONObject jsonObject2 = JsonSearch.findKey(fileContent2, "blackAttach");
        System.out.println("json3中包含blackAttach的JSON:" + jsonObject2);
        System.out.println("json3中的blackAttach:" + jsonObject2.getString("blackAttach"));
        System.out.println();

        //获取json3文件内容
        String filePath3 = "F:\json\json3.json";
        String fileContent3 = new String(Files.readAllBytes(Paths.get(filePath3)), StandardCharsets.UTF_8);
        //json字符串中查找blackAttach所在的json对象返回
        JSONObject jsonObject3 = JsonSearch.findKey(fileContent3, "blackAttach");
        System.out.println("json3中包含blackAttach的JSON:" + jsonObject3);
        System.out.println("json3中的blackAttach:" + jsonObject3.getString("blackAttach"));
    }
}

输出:

json1中包含blackAttach的JSON:{"allowAttach":"txt","children":[{"id":"flexpanel1","type":"flexpanel","events":{},"properties":{"title":"flexpanel"}}],"id":"rootpanel","type":"rootpanel","blackAttach":"blackAttach_json1"}
json1中的blackAttach:blackAttach_json1

json3中包含blackAttach的JSON:{"allowAttach":"txt","blackAttach":"blackAttach_json2"}
json3中的blackAttach:blackAttach_json2

json3中包含blackAttach的JSON:{"allowAttach":"txt","children":[{"children":[],"id":"cardpanel1","type":"cardpanel","events":{},"properties":{"staticAttr":[{"name":"field1","value":"$NULL"}]}}],"id":"panel1","blackAttach":"blackAttach_json3"}
json3中的blackAttach:blackAttach_json3
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/922185.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号