How to template a json in java programming

 

问题

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

My Use case is I have a json file but I have to share only few of them to client. Ex: Consider the source json file as shown below.

{

"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 below output

{

"personalInformation": {

"nameOfEmployee": "XYZ",

"ageOfEmployee": 24

},

"educationalInformation": {

"college": "ppppp",

"study": "b.tech"

}

}

And for other clients also the use case is same, 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.

解答

需要将多层json 输出成多种 json 格式。Json Path 可以实现,但是使用起来还是比较麻烦。

Java 下的开源包 SPL 很容易写,只要三句:


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 提供了 JDBC 供 Java 调用,把上面的脚本存为 jsonparse.splx,在 Java 中以存储过程的方式调用脚本文件:

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

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

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

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

问答搜集