How can you write raw JSON through Jackson JsonGenerator?

I want to generate a JSON string in the following structure using the Jackson API (JsonFactory, JsonGenerator). How can i do this?

Expected:

{ "api": { "Salutaion": "Mr", "name": "X" }, "additional": { "Hello", "World" } } 

Actual:

 { "api": "{ \"Salutaion\": \"Mr\", \"name\": \"X\" }", "additional": "{ \"Hello\", \"World\" }" } 

The values โ€‹โ€‹of the api and optional attributes will be available to me as String. Should I use writeObjectField (as follows)?

 jGenerator.writeObjectField("api", apiString); 

After creating the jGenerator object, how to get the final constructed representation of a JSON Object string?

 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonGenerator jGenerator = jfactory.createJsonGenerator(outputStream); jGenerator.writeStartObject(); jGenerator.writeObjectField("api", apiString); jGenerator.writeObjectField("additional", additionalString); jGenerator.writeEndObject(); jGenerator.close(); outputStream.close(); outputStream.toString() 

OutputStream.toString () gives a json string, but double quotes (") in apiString get the escape character prefix \

Is it correct?

+5
source share
1 answer

Assuming apiString and additionalString are references to String objects with JSON content, you'll want to write them raw, i.e. their content directly. Otherwise, you will serialize them as JSON strings, and Jackson will need to avoid any matching characters.

for instance

 jGenerator.writeFieldName("api"); jGenerator.writeRawValue(apiString); 

for api , and the same for additional .

+11
source

Source: https://habr.com/ru/post/1235391/


All Articles