【发布时间】:2020-06-10 23:24:33
【问题描述】:
如何从给定的 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]}
【问题讨论】:
-
@HarshalParekh - 添加了输出细节
-
你的字符串可以有 JSON 数组吗?
-
目前,您的字符串的最大深度为 4。
{}根据 JSON 计为一个级别。 -
第 2 级的输出是什么?
-
递归结构需要递归解决方案。每次点击“{”时,递归调用 self。当你点击“}”时,返回。
标签: java json regex pattern-matching matcher