英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论