Get List of Keys in Complex JSON Object (Java 8)

Question

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

I am dealing with a JSON file 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?

Answer

The computing task is to output field names of all levels in JSON records of indefinite number of levels. The code will be lengthy if you try to handle such a scenario in Java.

It is convenient to do this in SPL, the open-source Java package. Three lines of code are enough:

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 offers JDBC driver to be invoked by Java. Just store the above SPL script as jsonkeys.splx and invoke it in Java as you call a stored procedure:

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

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

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

View SPL source code.