如何在Java中打印原始请求的JSON主体,而不进行任何修改?

huangapple go评论80阅读模式
英文:

how to print Original request body JSON without any modification in java?

问题

通常我使用ObjectMapper来打印请求体,但这种方式会移除空格并将对象一行打印成字符串,示例:

如果我发送这样的请求体:

{
   "Header" : "value"
}

然后我使用objectMapper来打印那个对象:

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(requestBody)

输出会是这样的:

{"Header":"value"}

如何打印原始请求体而没有任何修改?

英文:

Normally to print out request body i using ObjectMapper, but this way removing space and printing object to string in one line, example :

if i send request body like this :

{
   "Header" : "value"
}

and i using objectMapper to print that object

ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(requestBody)

the out put is like this :

{"Header":"value"}

how to print Original request body without any modification ?

答案1

得分: 1

我不确定您是否可以将其以原始形式打印出来,但您可以进行漂亮的打印。
使用Jackson的对象映射器,您可以像这样操作:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
System.out.println(json);

或者

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(body);
System.out.println(json);
英文:

I'm not sure if you can print it in it's original form but you can pretty print it.
With Jackson's Object Mapper, you can do something like:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
System.out.println(json);

or

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(body);
System.out.println(json);

答案2

得分: 0

我认为你无法在不使用任何框架的情况下完成这个任务。

但是,如果你启用了prettyPrinting选项,你可以使用Gson来实现。示例代码如下:

Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .create();

prettyPrintedString = gson.toJson(requestBody, Object.class);
英文:

I don't think you can do this without using any framework.

But you can use the gson for this if you enable the prettyPrinting option. Example:

Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .create();

prettyPrintedString = gson.toJson(requestBody, Object.class);

huangapple
  • 本文由 发表于 2020年9月30日 20:52:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64138003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定