json按照路径JsonPath解析映射,替换指定位置的键名或键值

1. 使用到的依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.31</version>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.8.0</version>
        </dependency>

使用了fastjson和json-path,两者结合使用。

2. 代码部分

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.util.*;

public class TestDemo {
    @Test
    public void test1() {
        String json = "{\"points\":{\"point_1\":1,\"point_2\":2},\"id\":\"666\",\"time\":1688054681000}";
        System.out.println(json);

        List<DataMappingInfo> list1 = new ArrayList<>();

        DataMappingInfo dataMappingInfo = new DataMappingInfo();
        dataMappingInfo.setPath("$.id");
        dataMappingInfo.setMappingType(VALUE_MAPPING);
        Map<String, String> map = new HashMap<>();
        map.put("666", "6666");
        dataMappingInfo.setMappingValue(map);
        list1.add(dataMappingInfo);

        DataMappingInfo dataMappingInfo1 = new DataMappingInfo();
        dataMappingInfo1.setPath("$.points");
        dataMappingInfo1.setMappingType(KEY_MAPPING);
        Map<String, String> map1 = new HashMap<>();
        map1.put("point_2", "point_replace");
        dataMappingInfo1.setMappingValue(map1);
        list1.add(dataMappingInfo1);
        Object o = praseData(json, list1);
        System.out.println(o);
    }

    private final static String KEY_MAPPING = "KEY_MAPPING";

    private final static String VALUE_MAPPING = "VALUE_MAPPING";

    public static Object praseData(String json, List<DataMappingInfo> dataMappingInfos) {
        Object jsonParse = JSONObject.parse(json);
        //在这里判断传入的字符串是json对象还是json数组
        if (jsonParse instanceof JSONObject) {
            return dataFormat(jsonParse.toString(), dataMappingInfos);
        } else if (jsonParse instanceof JSONArray) {
            JSONArray dataArray = (JSONArray) jsonParse;
            List<String> resList = new ArrayList<>();
            dataArray.forEach(data -> {
                String res = dataFormat(JSONObject.toJSONString(data), dataMappingInfos);
                resList.add(res);
            });
            return resList;
        } else {
            throw new RuntimeException("The input json format is wrong");
        }

    }

    public static String dataFormat(String json, List<DataMappingInfo> dataMappingInfos) {
        DocumentContext documentContext = JsonPath.parse(json);
        dataMappingInfos.forEach(dataMappingInfo -> {
            String path = dataMappingInfo.getPath();
            Map<String, String> mappingValue = dataMappingInfo.getMappingValue();
            //获取json字符串的所有路径
            JSONObject jsonObject = JSON.parseObject(json);
            Map<String, Object> allPaths = JSONPath.paths(jsonObject);
            JsonPath jsonPath = JsonPath.compile(path);
            switch (dataMappingInfo.getMappingType()) {
                case KEY_MAPPING:
                    Map dataMap = (Map) JsonPath.read(json, path);
                    mappingValue.keySet().forEach(key -> {
                        if (allPaths.containsKey(path) && dataMap.containsKey(key)) {
                            documentContext.renameKey(jsonPath, key, mappingValue.get(key));
                        }
                    });
                    break;
                case VALUE_MAPPING:
                    String value = JsonPath.read(json, path).toString();
                    mappingValue.keySet().forEach(key -> {
                        if (Objects.equals(key, value) && allPaths.containsKey(path)) {
                            documentContext.set(jsonPath, mappingValue.get(key));
                        }
                    });
                    break;
                default:
                    break;
            }
        });
        return documentContext.jsonString();
    }
}

@Data
class DataMappingInfo {
    private String mappingType;
    private String path;
    private Map<String, String> mappingValue;
}
输入:
{"points":{"point_1":1,"point_2":2},"id":"666","time":1688054681000}

输出:
{"id":"6666","time":1688054681000,"points":{"point_1":1,"point_replace":2}}

支持传入json对象或者是json数组,解析json数组按字符串处理。
要映射替换key时,json的路径打到要替换的key的上一层路径,要替换value时,json的路径达到要替换的key上;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值