首页 > 解决方案 > 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和其他方式没有运气。任何帮助,将不胜感激。谢谢!

标签: jsonspring-restdocs

解决方案


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

推荐阅读