SpringREST文档json请求和响应格式
使用SpringREST文档json请求和响应格式,json,spring-restdocs,Json,Spring Restdocs,使用预处理器时产生的json如下所示: { "testId" : "message-1", "testType" : "TYPE", "nestedList" : [ { "nestedTestId" : 5, "nestedTestCode" : 2, "anotherNestedList" : [ { "anotherNestedFirst" : [ { "anotherId" : 1, "anotherValu
预处理器时产生的json如下所示:
{
"testId" : "message-1",
"testType" : "TYPE",
"nestedList" : [ {
"nestedTestId" : 5,
"nestedTestCode" : 2,
"anotherNestedList" : [ {
"anotherNestedFirst" : [ {
"anotherId" : 1,
"anotherValue" : "VALUE_1",
"anotherDescription" : null
}, {
"anotherId" : 2,
"anotherValue" : "VALUE_2",
"anotherDescription" : "DESCRIPTION"
} ]
} ]
} ]
}
我希望它看起来像这样:
大括号是由大多数在线json格式化程序格式化的带有略微缩进(两个空格)列表的换行符
尝试使用预处理器
replacePattern
和其他方法,但没有成功。
任何帮助都将不胜感激。谢谢 SpringRESTDocs在默认配置中使用Jackson漂亮地打印JSON请求和响应。您可以通过编写自己的自定义漂亮打印行为并创建使用它的预处理器来自定义此行为:
OperationPreprocessor prettyPrint = new ContentModifyingOperationPreprocessor((content, contentType) -> {
ObjectMapper objectMapper = new ObjectMapper();
PrettyPrinter prettyPrinter = new DefaultPrettyPrinter()
.withArrayIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
try {
return objectMapper.writer(prettyPrinter).writeValueAsBytes(objectMapper.readTree(content));
}
catch (IOException ex) {
return content;
}
});
上面的关键是将数组压头配置为使用换行,而不是默认的空格
然后,在记录操作时,您可以使用prettyPrint
:
mockMvc.perform(get("/example")).andExpect(status().isOk())
.andDo(document("example", preprocessRequest(prettyPrint), preprocessResponse(prettyPrint)));
mockMvc.perform(get("/example")).andExpect(status().isOk())
.andDo(document("example", preprocessRequest(prettyPrint), preprocessResponse(prettyPrint)));