Java Fastjson 替換指定屬性 & JQ風格


Fastjson   是一個 Java 庫,可以將 Java 對象轉換為 JSON 格式,當然它也可以將 JSON 字符串轉換為 Java 對象。

 

功能: 在不知道JSON格式的情況下,根據路徑替換屬性。

 

首先添加依賴,因為我們需要這個庫。

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

添加一個測試工具類 JsonUtil

package cn.flkj.sshluciaextension.utils;

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

/**
 * @author : 州長在手 2021/3/1 下午4:11
 */
public class JsonUtil {

    // --------------------------------- NO ARRAY ---------------------------------
//    public static <T> JSONObject JsonReplace(JSONObject json, String[] jsonPath, T content) {
//        return JsonReplaceHelper(json, jsonPath, content, 1);
//    }
//
//    public static <T> JSONObject JsonReplaceHelper(JSONObject json, String[] jsonPath, T content, int index) {
//        if (index == jsonPath.length) {
//            return json.fluentPut(jsonPath[index - 1], content);
//        }
//        JSONObject jsonSub = json.getJSONObject(jsonPath[index - 1]);
//        JSONObject jsonSubX = JsonReplaceHelper(jsonSub, jsonPath, content, index + 1);
//        json.fluentPut(jsonPath[index - 1], jsonSubX);
//        return json;
//    }

    // --------------------------------- ARRAY ---------------------------------
    public static <T> void JsonReplace(JSONObject json, String[] jsonPath, T content) {
         JsonReplaceHelper(json, jsonPath, content, 1);
    }

    public static <T> JSONObject JsonReplaceHelper(JSONObject json, String[] jsonPath, T content, int index) {
        String subPath = jsonPath[index - 1];
        // 遞歸結束狀態,返回給上一次遞歸需要的數據
        if (index == jsonPath.length) {
            if (!subPath.contains("[")) {
                return json.fluentPut(jsonPath[index - 1], content);
            } else {
                int number = Integer.parseInt(subPath.substring(subPath.indexOf("[") + 1, subPath.indexOf("]")));
                String subPathX = subPath.substring(0, subPath.indexOf("["));
                JSONArray subArray = json.getJSONArray(subPathX);
                subArray.remove(number);
                subArray.fluentAdd(number, content);
                json.fluentPut(subPathX, subArray);
                return json;
            }
        }
        // 是否是數組
        if (!subPath.contains("[")) {
            JSONObject jsonSub = json.getJSONObject(subPath);
            JSONObject jsonSubX = JsonReplaceHelper(jsonSub, jsonPath, content, index + 1);
            json.fluentPut(subPath, jsonSubX);
            return json;
        } else {
            // 數組的第幾個
            int number = Integer.parseInt(subPath.substring(subPath.indexOf("[") + 1, subPath.indexOf("]")));
            // 包含數組的真實鍵
            String subPathX = subPath.substring(0, subPath.indexOf("["));
            JSONArray subArray = json.getJSONArray(subPathX);
            JSONObject jsonSub = subArray.getJSONObject(number);
            JSONObject jsonSubX = JsonReplaceHelper(jsonSub, jsonPath, content, index + 1);
            subArray.remove(number);
            subArray.fluentAdd(number, jsonSubX);
            json.fluentPut(subPathX, subArray);
            return json;
        }
    }
}
package cn.flkj.sshluciaextension.utils;

import cn.flkj.sshluciaextension.shellcommand.ShellCommand;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.math.ec.ScaleYNegateXPointMap;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @author : 州長在手 2021/3/1 下午4:15
 */
class JsonUtilTest {
    //
    @Test
    public void testJsonReplace(){
        String jsonStr = ShellCommand.readingFile("static/config.txt");
        // System.out.println(jsonStr);
        JSONObject json = JSON.parseObject(jsonStr);
        System.out.println("old: "+json);
     // 需要替換屬性的路徑; String rep
= "data.data[0].payload.data[1].config[0]";
// 替換的屬性 String con
= "替換成功"; JsonUtil.JsonReplace(json,rep.split("\\."),con); System.out.println("new: "+json); } }

 

測試用例:

{
    "data":{
        "data":[
            {
                "payload":{
                    "data":[
                        {
                            "axss":"aaaaaa",
                            "config":[
                                "-----------------------"
                            ]
                        },
                        {
                            "axss":"aaaaaa",
                            "config":[
                                "需要替換"
                            ]
                        }
                    ]
                }
            },
            {
                "payload":{
                    "data":{
                        "axss":"aaaaaa",
                        "config":"xxxxx"
                    }
                }
            }
        ]
    }
}

 

 

測試截圖:

 


免責聲明!

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



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