Search code examples
javajackson2

How to write to raw string with jackson 2


I want to write an object to a raw json String. for example i have one class

class Tiger{
    String name;
    int age;
}

Tiger tiger = new Tiger("red", 12);

Then i use ObjectMapper of jackson to write it to string

ObjectMapper objectMapper = new ObjectMapper();
String result = objectMapper.writeValueAsString(tiger);

The result is:

 "{"name":"red","age":12}"

But i want to write the object to raw json string like this:

"{\"name\":\"red\",\"age\":12}"

I know that we can create a function to transform the normal string to raw string by adding "\", but i wonder is there any better solution for this?


Solution

  • You can write the output as json again, which will get it escaped:

    String result = objectMapper.writeValueAsString(
                          objectMapper.writeValueAsString(tiger));
    //outputs: "{\"name\":\"red\",\"age\":12}"