Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you write raw JSON through Jackson's JsonGenerator?

Tags:

java

json

jackson

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

Expected:

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

Actual:

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

The values of the attributes api & additional will be available to me as String. Should i be using writeObjectField (as follows) ?

jGenerator.writeObjectField("api", apiString);

After constructing the jGenerator object, how do i get the final constructed JSON Object's String representation ?

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()

The outputStream.toString() gives a json string but the double quotes (") in the apiString are getting prefixed with an escape character \

Is this the right way ?

like image 296
yathirigan Avatar asked Nov 06 '15 18:11

yathirigan


People also ask

How does Jackson build JSON?

We can create a JSON in the Jackson library using the JsonNodeFactory, it can specify the methods for getting access to Node instances as well as the basic implementation of the methods. We can use the set() and put() methods of ObjectNode class to populate the data.

What is raw JSON data?

Raw JSON text is the format Minecraft uses to send and display rich text to players. It can also be sent by players themselves using commands and data packs. Raw JSON text is written in JSON, a human-readable data format.

Is JSON A Jackson?

Jackson is a solid and mature JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON response objects with a lot of flexibility.


1 Answers

Assuming apiString and additionalString are references to String objects with JSON content, you'll want to write them raw, ie. their content directly. Otherwise, you're serializing them as JSON strings and Jackson will need to escape any relevant characters.

For example

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

for api, and the same for additional.

like image 85
Sotirios Delimanolis Avatar answered Oct 20 '22 01:10

Sotirios Delimanolis