简体   繁体   English

ObjectMapper 在将字符串写入输出流时添加转义字符

[英]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.我有下面的代码,我使用 Jackson 的 ObjectMapper 将字符串写入 output stream。

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.当我运行这段代码时, output stream 打印出以下字符串,其中有额外的转义字符。

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

How can I avoid the escape characters here?我怎样才能避免这里的转义字符? I am not using ObjectMapper.writeValueAsString but still they get printed.我没有使用 ObjectMapper.writeValueAsString 但它们仍然被打印出来。 Appreciate any help.感谢任何帮助。

You are serializing a Java string as JSON string.您正在将 Java 字符串序列化为JSON 字符串。 JSON strings must start and end with " and any embedded quotes must be escaped. (ref: https://json.org ) JSON 字符串必须以"开头和结尾,并且必须转义任何嵌入的引号。(参考: https://json.org

You have two options:你有两个选择:

  1. Print the string directly, without serializing via ObjectMapper直接打印字符串,不通过 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序列化一个 object,例如 Map,到一个 JSON 字符串

    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.也可以定义自定义 class 来表示您的 JSON 结构。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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