I have a Java application method which accepts InputStream
as its input parameter. This input parameter includes the large customer data in JSON format. I have to create the wrapper elements to this JSON to match the standard.
The user provided JSON looks something like this:
[
{
"name": "Batman",
"age": 30,
"city": "Gotham"
},
{
"name": "Superman",
"age": 33,
"city": "Gotham"
}
]
After creating the wrapper my JSON should look something like this (Expected Output):
{
"type": "customerDocument",
"creationDate": "2005-07-11T11:30:47.0Z",
"customerBody": {
"customerList": [
{
"name": "Batman",
"age": 30,
"city": "Gotham"
},
{
"name": "Superman",
"age": 33,
"city": "Gotham"
}
]
}
}
I am creating the same using following approach:
//Method to frame the outer wrapper elements for the JSON.
private InputStream generateJsonWrapper(final InputStream usersList) throws IOException {
final JsonFactory jsonfactory = new JsonFactory();
final StringWriter jsonObjectWriter = new StringWriter();
final JsonGenerator jsonGenerator = jsonfactory.createGenerator(jsonObjectWriter);
jsonfactory.createGenerator(jsonObjectWriter);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("type", "customerDocument");
jsonGenerator.writeStringField("creationDate", Instant.now().toString());
jsonGenerator.writeObjectFieldStart("customerBody");
jsonGenerator.writeFieldName("customerList");
jsonGenerator.writeRawValue(IOUtils.toString(usersList, StandardCharsets.UTF_8));
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
jsonGenerator.flush();
jsonGenerator.close();
return new ByteArrayInputStream(jsonObjectWriter.toString().getBytes(StandardCharsets.UTF_8));
}
The above provided approach works fine and able to get the required JSON but here I need to convert the provided usersList to String and add it. Then finally the String need to be converted to InputStream.
Is there any approach using which I can avoid converting the InputStream usersList
to String while adding writeRaw
?