I'm very new working java with json. Couldn't find relevant solutions. That's why posting this question. I have json with property name as value in it. How to convert this property name as attribute and restructured in array. Any help would be much appreciated.
Following is my json file:
INPUT JSON:
{
"payload": {
"giata": {
"435185": [
"2019-11-27T14:34:32.368197Z"
]
},
"dod1": {
"A0947863": [
"2019-11-27T14:34:32.368197Z"
]
},
"gr": {
"A0947863": [
"2019-11-27T14:34:32.368197Z",
"2021-04-27T06:13:12.841968Z",
"2021-04-27T06:13:21.640612Z",
"2021-04-27T06:13:28.439001Z",
"2021-04-27T06:13:43.487103Z",
"2021-04-27T06:13:49.770269Z"
]
}
}
}
Expected JSON :
{
"payload": {
"sources": [
{
"source": "giata",
"code": "435185",
"version": [
"2019-11-27T14:34:32.368197Z"
]
},
{
"source": "dod1",
"code": "A0947863",
"version": [
"2019-11-27T14:34:32.368197Z"
]
},
{
"source": "gr",
"code": "A0947863",
"version": [
"2019-11-27T14:34:32.368197Z",
"2021-04-27T06:13:12.841968Z",
"2021-04-27T06:13:21.640612Z",
"2021-04-27T06:13:28.439001Z",
"2021-04-27T06:13:43.487103Z",
"2021-04-27T06:13:49.770269Z"
]
}
]
}
}
Code:
package com.tui.structure_json;
import java.util.Map;
import java.util.Set;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class App
{
public static void main( String[] args )
{
String yourJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"giata\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"dod1\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"gr\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\",\r\n" +
" \"2021-04-27T06:13:21.640612Z\",\r\n" +
" \"2021-04-27T06:13:28.439001Z\",\r\n" +
" \"2021-04-27T06:13:43.487103Z\",\r\n" +
" \"2021-04-27T06:13:49.770269Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
JsonElement element = JsonParser.parseString(yourJson);
JsonObject obj = element.getAsJsonObject(); //since you know it's a JsonObject
Set<Map.Entry<String, JsonElement>> entries = obj.entrySet();//will return members of your object
for (Map.Entry<String, JsonElement> entry: entries) {
System.out.println(entry.getValue());
}
}
}