Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write to raw string with jackson 2

Tags:

java

jackson2

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?

like image 684
shinobitiger310 Avatar asked Feb 04 '26 16:02

shinobitiger310


1 Answers

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}"
like image 105
ernest_k Avatar answered Feb 06 '26 04:02

ernest_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!