简体   繁体   中英

ObjectMapper Adds Escape Characters When Writing String to Outputstream

I have the below piece of code where I write a string to an output stream with Jackson's ObjectMapper.

OutputStream outputStream = new PrintStream(System.out);
ObjectMapper objectMapper = new ObjectMapper();
String output = "{\"test\":\"mytest/123\"}";
objectMapper.writeValue(outputStream, output);

When I run this code, the output stream prints the following string, where there are additional escape characters.

"{\"vfi\":\"test/mytest/123\"}"

How can I avoid the escape characters here? I am not using ObjectMapper.writeValueAsString but still they get printed. Appreciate any help.

You are serializing a Java string as JSON string. JSON strings must start and end with " and any embedded quotes must be escaped. (ref: https://json.org )

You have two options:

  1. Print the string directly, without serializing via ObjectMapper

    OutputStream outputStream = new PrintStream(System.out); String output = "{\"test\":\"mytest/123\"}"; outputStream.println(output);
  2. Serialize an object, eg Map, to a JSON string

    OutputStream outputStream = new PrintStream(System.out); ObjectMapper objectMapper = new ObjectMapper(); Map<String, String> output = Map.of("test", "mytest/123"); objectMapper.writeValue(outputStream, output);

    It's also possible to define a custom class to represent your JSON structure. Depending on the complexity of your structure and other requirements, this could be the preferrable option.

     class MyOutput { private final String test; public MyOutput(final String test) { this.test = test; } public String getTest() { return test; } } OutputStream outputStream = new PrintStream(System.out); ObjectMapper objectMapper = new ObjectMapper(); MyOutput output = new MyOutput("mytest/123"); objectMapper.writeValue(outputStream, output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM