Get list of keys in Complex JSON Object (Java 8)

 

问题

https://stackoverflow.com/questions/64011499/get-list-of-keys-in-complex-json-object-java-8

I am dealing with a JSON that looks like this :-

{

"key1": {

"key1.1": {

"nestedkey1": "something",

"nestedkey2": "something",

"nestedkey3": "Something"

},

"key1.2": {

"nestedkey1": "something",

"nestedkey2": "something",

"nestedkey3": "Something"

}

},

"key2": {

"key2.1": {

"nestedkey1": "something",

"nestedkey2": "something",

"nestedkey3": "Something"

},

"key2.2": {

"nestedkey1": "something",

"nestedkey2": "something",

"nestedkey3": "Something"

}

}...

And I don't know all the keys. I wish to obtain all the keys so that I can create a Map<String, Object> out of this. That map should look something like ("key1" ->Corresponding object)...

Is there a simple way to do this in Java?

解答

将不确定层级的json记录,输出所有层级的字段名。用Java 实现代码较长。

Java 下的开源包 SPL 很容易写,只要 3 行:


A

B

1

=i=0,json(file("records.json").read())

2

func recurse(r)

>i+=1,r.fno().run(tmp=eval("r.#"/~),B1=B1.to(:i-1)|r.fname(~),output(B1.concat("->")),if(ifr(tmp),func(recurse,tmp),(B1=B1|tmp)))

3

=func(recurse,A1)

SPL 提供了 JDBC 供 Java 调用,把上面的脚本存为 jsonkeys.splx,在 Java 中以存储过程的方式调用脚本文件:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call jsonkeys()");
st.execute();

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集