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

一、遇到的问题:

要获取的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如下:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>

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

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

public class JsonSearch {
    /**
     * 从json字符串中查询含有searchKey的JSON对象
     *
     * @param jsonObject   待查找的json对象
     * @param searchKey    要查找的key
     * @return 返回含有searchKey的json对象
     */
    public static JSONObject findKey(JSONObject jsonObject, String searchKey) {
        JSONObject result = null;
        for (Map.Entry<String, Object> 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;
    }

    /**
     * 从json字符串中查询含有searchKey的JSON对象
     *
     * @param jsonStr    json字符串
     * @param searchKey  要查找的key
     * @return 返回含有searchKey的json对象
     */
    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<String, Object> 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值