java通過key鏈之間獲取JSON中的值


JSON是一種嵌套數據結構,無規則的模式,獲取json中的值只能通過一層一層的get,在實際工作中非常不便,在fastjson的基礎上,我寫了一個工具類,可以直接通過key鏈直接獲取對應的值

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) throws IOException {
        String jsonStr = "{\"job\":{\"content\":[{\"reader\":{\"name\":{\"a\":\"b\"}}}]}}";
        String keyPath = "job.content[0].reader.name.a";
        Object json = getJsonString(jsonStr, keyPath);
        System.out.println(json);


    }

    //判斷一個字符串是不是數字
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    //將keyPath分割成數組
    public static String[] customSplit(String oldStr) {
        List<String> strings = new ArrayList<>();
        String[] split = oldStr.split("\\.");
        for (String s : split) {
            if (s.contains("[")) {
                String[] subS = s.split("\\[|\\]");
                Collections.addAll(strings, subS);
            } else {
                strings.add(s);
            }
        }
        return strings.toArray(new String[0]);
    }

    //最終的value不一定是string,但返回string具有最大的普適性,相比返回JSON或Object更方便使用
    public static String getJsonString(String jsonStr, String keyPath) {
        String[] keyArray = customSplit(keyPath);
        JSON curResult = null;
        JSON curJson;
        if (isInteger(keyArray[0])) {
            curJson = JSON.parseArray(jsonStr);
        } else {
            curJson = JSON.parseObject(jsonStr);
        }
        for (int i = 0; i < keyArray.length; i++) {
            int j = i + 1;
            //判斷父Json當前類型,JSONObject
            if (curJson instanceof JSONObject) {
                //判斷子Json類型,分兩種情況,最后一個key是無法確認其value類型的,默認返回string
                if (j == keyArray.length) {
                    return ((JSONObject) curJson).getString(keyArray[i]);
                }
                //如果不是最后一個key,可以根據其后的key的類型來判斷當前key對應的value類型
                if (isInteger(keyArray[j])) {
                    curResult = ((JSONObject) curJson).getJSONArray(keyArray[i]);
                } else {
                    curResult = ((JSONObject) curJson).getJSONObject(keyArray[i]);
                }
            } //判斷父Json當前類型,JSONArray
            else {
                //判斷子Json類型,最后一個key默認返回string
                if (j == keyArray.length) {
                    return ((JSONArray) curJson).getString(Integer.parseInt(keyArray[i]));
                }
                if (isInteger(keyArray[j])) {
                    curResult = ((JSONArray) curJson).getJSONArray(Integer.parseInt(keyArray[i]));
                } else {
                    curResult = ((JSONArray) curJson).getJSONObject(Integer.parseInt(keyArray[i]));
                }
            }
            curJson = curResult;
        }
        return curResult.toJSONString();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM