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 и другими средствами безуспешно. Любая помощь будет оценена по достоинству. Спасибо!


person Catalino Comision    schedule 04.03.2020    source источник


Ответы (1)


Spring REST Docs использует Джексона в конфигурации по умолчанию для красивой печати запросов и ответов 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)));
person Andy Wilkinson    schedule 06.03.2020