Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SpringREST文档json请求和响应格式_Json_Spring Restdocs - Fatal编程技术网

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)));