Json根据映射配置读取数据创建新数据(数据转换 系统集成对接)

 public static void main(String[] args) {
        json = "{\"data\":{\"subList\":[{\"materialClass\":23068302752852482},{\"materialClass\":23068302752852481}]}}";
        System.out.println(json);
        Object object = JSON.parse(json);
        JSONObject newJSONObject = new JSONObject();

        String selectPath = "$.data.subList.materialClass";
        String newPath = "$.data.subList.materialClass";

        jsonReplaceMapKey(object, newJSONObject, selectPath, newPath);
        System.out.println(newJSONObject.toJSONString());

    }
private static void jsonReplaceMapKey(Object object, JSONObject newJSONObject, String selectPath, String newPath) {
        Object newObject = JSONPath.compile(selectPath).eval(object);
        // 构建插入对象
        if (newObject instanceof JSONArray) {
            JSONArray array = (JSONArray) newObject;
            List<Map<String, Object>> maps = new ArrayList<>();
            String[] strings = newPath.split("\\.");
            if (strings.length > 0) {
                array.forEach(c -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put(strings[strings.length - 1], c);
                    maps.add(map);
                });
                newPath = newPath.substring(0,  newPath.lastIndexOf("."));
            }
            newObject = maps;
        }
        JSONPath.set(newJSONObject, newPath, newObject);
    }

 

posted @ 2022-07-19 15:42  atliwen  阅读(200)  评论(1编辑  收藏  举报