How to Template a JSON in Java Programming

Question

Source:https://stackoverflow.com/questions/52167101/how-to-template-a-json-in-java-programming

My use case is that I have a JSON file but I have to share only some of them to client. Consider the source JSON file is like this:

{

"name": "XYZ",

"age": 24,

"education": {

"college": "ppppp",

"study": "b.tech",

"grade": 6.8

},

"friends": ["kkkk",

"bbbbbbbbbbb",

"jjjjjj"],

"dob":"01-08-1990"

}

For client 1 I have to share below output

{

"personalInfo": {

"name": "XYZ",

"age": 24,

"friendsNames": ["kkkk","bbbbbbbbbbb","jjjjjj"]

},

"educationalInfo": {

"college": "ppppp",

"study": "b.tech",

"grade": 6.8

}

}

For client 2 I have to share the following output:

{

"personalInformation": {

"nameOfEmployee": "XYZ",

"ageOfEmployee": 24

},

"educationalInformation": {

"college": "ppppp",

"study": "b.tech"

}

}

And same case for other clients. I have to skip some keys and give different names to the keys. How to dynamically do this by some kind of configuration. I used JSONPath to achieve this but removing few keys from JSON object is difficult. Any suggestions can be appreciated.

Answer

Your job is to output multilevel JSON data as multiple JSON formats. JSONPath can do this but the process is a hassle.

A simple alternative is to use SPL. SPL is a Java open-source package. You just need three lines of code to get the job done:

A

1

=json(file("data.json").read())

2

>(client1=json(([["personalInfo","educationalInfo"]]|[A1.array(~).new(name,age,friends:friendsNames)|A1.array(~).education]).record()(1)),client2=json(([["personalInformation","educationalInformation"]]|[A1.array(~).new(name:nameOfEmployee,age:ageOfEmployee)|A1.array(education).new(college,study)]).record()(1)))

3

return client1,client2

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as jsonparse.splx and invoke it in a Java application as you call a stored procedure:

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

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

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

View SPL source code.