You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Spring REST Docs为JSON数组的每个元素生成文档

How to Document Array Elements with Distinct Meanings in Spring REST Docs

If you need to document each element in a fixed-position JSON array (where each index maps to a specific, unique meaning), Spring REST Docs lets you target individual elements directly using their zero-based array index in the field path. Here's a step-by-step solution for your response array ["1525032694","300","true"]:

Step 1: Target Elements with Indexed Field Paths

In your test class, when configuring response field documentation, reference each array element using fieldWithPath and the element's index wrapped in square brackets. This lets you attach unique descriptions to every position in the array.

Example Test Implementation

import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;

// Inside your test method
this.mockMvc.perform(get("/your-target-endpoint"))
    .andExpect(status().isOk())
    .andDo(document("your-api-docs",
        responseFields(
            fieldWithPath("[0]").description("当前时间戳(字符串格式的Unix时间戳)"),
            fieldWithPath("[1]").description("下一次测量的间隔秒数(字符串格式的数字)"),
            fieldWithPath("[2]").description("布尔标识(字符串格式的布尔值,取值为`true`或`false`)")
        )
    ));

Step 2: Reuse Field Descriptors (Optional)

If you need to reference these field descriptions across multiple endpoints, extract them into a reusable set of FieldDescriptor objects to avoid duplication:

import org.springframework.restdocs.payload.FieldDescriptor;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;

public class ApiDocDescriptors {
    public static final FieldDescriptor[] MEASUREMENT_RESPONSE_FIELDS = {
        fieldWithPath("[0]").description("当前时间戳(字符串格式的Unix时间戳)"),
        fieldWithPath("[1]").description("下一次测量的间隔秒数(字符串格式的数字)"),
        fieldWithPath("[2]").description("布尔标识(字符串格式的布尔值,取值为`true`或`false`)")
    };
}

Then reference the reusable set in your tests:

.andDo(document("your-api-docs",
    responseFields(ApiDocDescriptors.MEASUREMENT_RESPONSE_FIELDS)
))

Key Tips

  • The indexed path notation ([0], [1], etc.) works for both request and response payload arrays in Spring REST Docs.
  • Be explicit about data types in your descriptions if elements are string representations of primitives (like your example uses string-formatted numbers/booleans instead of raw types).

内容的提问来源于stack exchange,提问作者pixel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:33:17