json - Spring Rest Docs json 请求和响应格式
问题描述
使用时生成的json Preprocessors
prettyPrint()
如下:
{
"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"
} ]
} ]
} ]
}
我希望它看起来像这样:
大括号是带有轻微(2 空格)缩进列表的换行符,由大多数在线 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"
}
]
}
]
}
]
}
尝试过Preprocessors
replacePattern
和其他方式没有运气。任何帮助,将不胜感激。谢谢!
解决方案
Spring REST Docs 在其默认配置中使用 Jackson 来漂亮地打印 JSON 请求和响应。您可以通过编写自己ContentModifier
的自定义漂亮打印行为并创建使用它的预处理器来自定义此行为:
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)));
推荐阅读
- python - 在python中没有列表的情况下导出最高和最低数字
- javascript - 如何在`before`钩子之前运行beforeEach
- reactjs - 我想在类组件中使用“react-hook-form”中的 { useForm }
- jetbrains-ide - 在 Rider 中为每个解决方案设置 .runsettings 路径
- c++ - 一个可由 1 个线程访问的数组,可以返回其他线程请求的数据
- nuxt.js - Nuxt 与 LocomotiveScroll 和 Gsap
- windows - 批处理脚本函数调用工作不正常
- vb6 - 与较新版本的 tlb 相关的 Microsoft Visual Basic 6 警告
- database - 文件“3050/var/lib/firebird/data/corp”的 CreateFile(打开)操作期间出现 I/O 错误。该系统找不到指定的路径
- java - 用java编写插入排序算法