Return 给定 JSON 给定级别的最大嵌套级别和项目列表

Return the maximum level of nesting and list of items at a given level from the given JSON

如何 return 给定 JSON 给定级别的最大嵌套级别和项目列表。我被要求不要使用任何第三方库。所以我尝试使用模式匹配但无法得到结果。

{
    "1" : {
       "A" :{}
    },
    "2" : {
       "A" :{}
       "B" : {
         "I" :{},
         "II":{}
       }
    },
    "3" : {}
}

我试过的代码:

public class NestedJson {

    public int depth(String data, int deptth){

        Pattern pattern = Pattern.compile("\"(.+)\"");
        Matcher matcher = pattern.matcher(data);

        List<String> list = new ArrayList<String>();
        while (matcher.find()) {
            list.add(matcher.group(1));
        }

        System.out.println(list.size());
        return list.size();

    }

    public static void main(String args[]){
     String data = "{\n" +
             "\t\"1\" : {\n" +
             "\t   \"A\" :{}\n" +
             "\t},\n" +
             "\t\"2\" : {\n" +
             "\t   \"A\" :{}\n" +
             "\t   \"B\" : {\n" +
             "\t     \"I\" :{},\n" +
             "\t     \"II\":{}\n" +
             "\t   }\n" +
             "\t},\n" +
             "\t\"3\" : {}\n" +
             "}";

        NestedJson nestedJson = new NestedJson();
        nestedJson.depth(data, 1);
    }
}

需要示例输出:

depth(data,1) -> {"max_level"= 3, items= [1,2,3]}
depth(data,2) -> {"max_level"= 3, items= [A,A,B]}

我会这样做,所以你不必再次扫描文本来要求不同的级别。

public final class NestedJson {
    private int maxLevel;
    private Map<Integer, List<String>> items = new HashMap<>();

    public NestedJson(String data) {
        int level = 0;
        for (Matcher m = Pattern.compile("\"([^\"]*+)\"|([{}])").matcher(data); m.find(); ) {
            if (m.start(1) != -1) {
                this.items.computeIfAbsent(level, k -> new ArrayList<>()).add(m.group(1));
                if (level > this.maxLevel)
                    this.maxLevel = level;
            } else if (m.group(2).charAt(0) == '{') {
                level++;
            } else {
                level--;
            }
        }
    }

    public int getMaxLevel() {
        return this.maxLevel;
    }
    public List<String> getItems(int level) {
        return this.items.get(level);
    }
}

测试

String data = "{\n" +
              "\t\"1\" : {\n" +
              "\t   \"A\" :{}\n" +
              "\t},\n" +
              "\t\"2\" : {\n" +
              "\t   \"A\" :{}\n" +
              "\t   \"B\" : {\n" +
              "\t     \"I\" :{},\n" +
              "\t     \"II\":{}\n" +
              "\t   }\n" +
              "\t},\n" +
              "\t\"3\" : {}\n" +
              "}";

NestedJson nestedJson = new NestedJson(data);
System.out.println("maxLevel = " + nestedJson.getMaxLevel());
for (int level = 1; level <= nestedJson.getMaxLevel(); level++)
    System.out.println("items(" + level + ") = " + nestedJson.getItems(level));

输出

maxLevel = 3
items(1) = [1, 2, 3]
items(2) = [A, A, B]
items(3) = [I, II]