I have a column in DB which stored data in following json format like below: {"ad002":"5601087282462117","be003":"{"1":"ABC","2":"DEF","3":"DEF"}","ze024":"18"}
I want to iterate the data without keys as there are thousand of keys in data and if some element found like be003 where it has further key values then all the values should be concatenate and return that value.
I tried below solution
JSONObject outerObject = new JSONObject(jsonInput); String ad002Value = outerObject.optString("ad002"); JSONObject be003Object = new JSONObject(outerObject.optString("be003"));
but here I need to depend in keys which is not required as there are thousand of keys. I need to further set values to some object.
CodePudding user response:
Use JSON library such as Josson to do the transformation.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(
"{"
" \"ad002\": \"5601087282462117\","
" \"be003\": \"{\\\"1\\\":\\\"ABC\\\",\\\"2\\\":\\\"DEF\\\",\\\"3\\\":\\\"DEF\\\"}\","
" \"ze024\": \"18\""
"}");
Transformation
JsonNode node = josson.getNode(
"entries()" // Step 1
".field(value"
" .if(startsWith('{')," // Assume it is an object
" json().entries().value.@join(),"
" ?)"
" )" // Step 2
".map(key::value)" // Step 3
".mergeObjects()"); // Final step
System.out.println(node.toPrettyString());
Output
{
"ad002" : "5601087282462117",
"be003" : "ABCDEFDEF",
"ze024" : "18"
}
Path Trace
You can use function getPathTrace()
to see the output of each step.
PathTrace trace = josson.getPathTrace(...)
Step 1 output
[ {
"key" : "ad002",
"value" : "5601087282462117"
}, {
"key" : "be003",
"value" : "{\"1\":\"ABC\",\"2\":\"DEF\",\"3\":\"DEF\"}"
}, {
"key" : "ze024",
"value" : "18"
} ]
Step 2 output
[ {
"key" : "ad002",
"value" : "5601087282462117"
}, {
"key" : "be003",
"value" : "ABCDEFDEF"
}, {
"key" : "ze024",
"value" : "18"
} ]
Step 3 output
[ {
"ad002" : "5601087282462117"
}, {
"be003" : "ABCDEFDEF"
}, {
"ze024" : "18"
} ]