how can i create a JSON string from Json array of objects like below in Java using JSON object
{
header: [
{
"key" : "numberOfRecords",
"value" : "122"
"valueDataType" : "string"
},
{
"key" : "g_udit"
"value" : "1"
"valueDataType" : "string"
},
{
"key": "userNameId"
"value" : "155"
"valueDataType : "string"
}
]
}
expected JSON output requires only values
{
header :
{
"numberOfRecords" : "122",
"g_udit" : "1",
"userNameId" : "155"
}
}
Use JSON query language to transform the JSON structure. A single Josson query statement can do the job.
https://github.com/octomix/josson
Josson josson = Josson.fromJsonString(
"{" +
" \"header\": [" +
" {" +
" \"key\" : \"numberOfRecords\"," +
" \"value\" : \"122\"," +
" \"valueDataType\" : \"string\"" +
" }," +
" { " +
" \"key\" : \"g_udit\"," +
" \"value\" : \"1\"," +
" \"valueDataType\" : \"string\"" +
" }," +
" {" +
" \"key\": \"userNameId\"," +
" \"value\" : \"155\"," +
" \"valueDataType\" : \"string\"" +
" }" +
" ]" +
"}");
JsonNode node = josson.getNode("map(header.map(key::value).mergeObjects())");
Output
{
"header" : {
"numberOfRecords" : "122",
"g_udit" : "1",
"userNameId" : "155"
}
}
First of all you should use any json
framework to read and write files. You can use jacskon-utils to use Jackson
and make it much simpler to use.
Then you have to define the data classes from input and output types. And finally, convert the data.
@Getter
class InputData {
@JsonProperty("header")
private List<Header> headers;
@Getter
public static class Header {
private String key;
private String value;
private String valueDataType;
}
}
@Setter
class OutputData {
@JsonProperty("header")
private Map<String, String> headers;
}
public static void main(String... args) throws Exception {
InputData inputData = readData(new File("c:/in.json"));
OutputData outputData = createOutputData(inputData);
writeData(new File("c:/out.json"), outputData);
}
private static InputData readData(File file) throws Exception {
try (InputStream in = new FileInputStream(file)) {
return JacksonUtils.readValue(in, InputData.class);
}
}
private static void writeData(File file, OutputData outputData) throws Exception {
try (OutputStream out = new FileOutputStream(file)) {
JacksonUtils.prettyPrint().writeValue(outputData, out);
}
}
private static OutputData createOutputData(InputData inputData) {
Map<String, String> headers = new LinkedHashMap<>();
inputData.getHeaders().forEach(header -> headers.put(header.getKey(), header.getValue()));
OutputData outputData = new OutputData();
outputData.setHeaders(headers);
return outputData;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.