首页 > 解决方案 > 在 JAVA 中重构 JSON 文件

问题描述

我从 JSON 文件中获得以下示例:

[
{
  "0":
  {
    "File":"file1.java",
    "Class":"com.ETransitionActionType",
    "Method":"values",
    "Annotation":"Not Found"
  }
},
{
  "1":
  {
    "File":"file2.java",
    "Class":"com.ETransitionParams",
    "Method":"values",
    "Annotation":"Not Found"
  }
},
{
  "2":
  {
    "File":"file3.java",
    "Class":"com.phloc.commons.id.IHasID",
    "Method":"getID",
    "Annotation":"Not Found"
  }
},
{
  "4":
  {
    "File":"file3.java",
    "Class":"com.ExecuteTransitionActionHandler",
    "Method":"createBadRequestResponse",
    "Annotation":"Not Found"
  }
},
{
  "5":
  {
    "File":"file3.java",
    "Class":"com.ExecuteTransitionActionHandler",
    "Method":"extractParametersFromAction",
    "Annotation":"Not Found"
  }
}]

如何使用 java 重构此文件,使其看起来像:

[{
    "file1.java": {
        "com.ETransitionActionType": {
            "values": {
                "Annotation": "Not Found"
            }
        }
    }
},
{
    "file2.java": {
        "com.ETransitionParams": {
            "values": {
                "Annotation": "Not Found"
            }
        }
    }
},
{
    "file3.java": {
        "com.phloc.commons.id.IHasID": {
            "getID": {
                "Annotation": "Not Found"
            }
        },
        "com.ExecuteTransitionActionHandler": {
            "getID": {
                "Annotation": "Not Found"
            },
            "extractParametersFromAction": {
                "Annotation": "Not Found"
            }
        }
    }
}
]

即遍历 JSON 文件,搜索它,只要“File”属性具有相同的值(例如“file3.java”),我们列出所有相关的类和方法,同样适用于“Class”属性,如果它有相同的名称,我们列出它里面的所有方法(所以这就像比较和排序“文件”和“类”属性的值)。我从 JSON 简单库开始,像下面的代码一样编写,但不知道如何更进一步!

Object object = (JSONArray)parser.parse(new FileReader("rawOutput.json"));            
JSONArray jsonArray =  (JSONArray) object;
for(int i = 0; i < jsonArray.size(); i++) {
    System.out.println(jsonArray.get(i));
    JSONObject jsonObject = (JSONObject)jsonArray.get(i);
    String c = jsonObject.get("" + i + "").toString();
}

有任何想法吗?非常感谢您的帮助!!!

标签: javajsonfile

解决方案


import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Foo {
    public static void main(String... args) throws IOException {
        String json = formatJson(new FileReader("rawOutput.json"));
        System.out.println(json);
    }

    public static String formatJson(Reader reader) throws IOException {
        // group array items by fileName
        final Function<List<Map<String, Object>>, Map<String, List<Object>>> groupByFileName =
                data -> data.stream().collect(Collectors.groupingBy(map -> (String)map.get("File"), TreeMap::new,
                        Collectors.mapping(Function.identity(), Collectors.toList())));

        // convert source item structure into required
        final Function<Map.Entry<String, List<Object>>, Map<String, Object>> convert = entry -> {
            Map<String, Map<String, Map<String, String>>> tmp = new LinkedHashMap<>();

            entry.getValue().stream()
                    .map(value -> (Map<String, String>)value)
                    .forEach(map -> {
                        Map<String, Map<String, String>> classes = tmp.computeIfAbsent(map.get("Class"), cls -> new TreeMap<>());
                        Map<String, String> methods = classes.computeIfAbsent(map.get("Method"), method -> new TreeMap<>());

                        map.entrySet().stream()
                                .filter(e -> !"Class".equals(e.getKey()) && !"Method".equals(e.getKey()) && !"File".equals(e.getKey()))
                                .forEach(e -> methods.put(e.getKey(), e.getValue()));
                    });

            return Collections.singletonMap(entry.getKey(), tmp);
        };

        ObjectMapper mapper = new ObjectMapper();

        // read json as array of Maps
        List<Map<String, Object>> data = Arrays.stream(mapper.readValue(reader, Map[].class))
                .map(map -> map.values().iterator().next())
                .map(item -> (Map<String, Object>)item)
                .collect(Collectors.toList());

        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(groupByFileName.apply(data).entrySet().stream()
                .map(convert).collect(Collectors.toList()));
    }
}

推荐阅读