Skip to content

Instantly share code, notes, and snippets.

@mat127
Last active August 20, 2025 20:03
Show Gist options
  • Save mat127/a7e1f12d6c942a0ed7aa091937404a33 to your computer and use it in GitHub Desktop.
Save mat127/a7e1f12d6c942a0ed7aa091937404a33 to your computer and use it in GitHub Desktop.
Spring RestDocs workaround for documenting nested arrays in the response
/*
* This provides a workaround for the https://github.com/spring-projects/spring-restdocs/issues/569
*
* The basic idea is to create a OperationResponsePreprocessor that will extract
* a subsection (described by a JSON pointer) from the original OperationResponse and allow
* to create snippets from it.
*/
@AllArgsConstructor
class OperationResponseSubsectionPreprocessor implements OperationResponsePreprocessor {
private ObjectMapper objectMapper;
private String jsonPointer;
@Override
public OperationResponse preprocess(final OperationResponse response) {
try {
final var originalJson = this.objectMapper.readTree(response.getContent());
final var subsectionJson = originalJson.at(jsonPointer);
final var subsectionContent = this.objectMapper.writeValueAsBytes(subsectionJson);
return new OperationResponseSubsection(response, subsectionContent);
}
catch (IOException e) {
throw new RuntimeException("error while extracting JSON subsection", e);
}
}
@AllArgsConstructor
private static class OperationResponseSubsection implements OperationResponse {
private final OperationResponse origin;
private final byte[] content;
@Override
public HttpStatus getStatus() {
return this.origin.getStatus();
}
@Override
public int getStatusCode() {
return this.getStatus().value();
}
@Override
public HttpHeaders getHeaders() {
return this.origin.getHeaders();
}
@Override
public byte[] getContent() {
return this.content;
}
@Override
public String getContentAsString() {
return new String(this.getContent());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment