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

如何在Swagger中配置SourcePoints为多元素ArrayList展示

Fixing Swagger's Single-Element Array Example for Your Post Request Body

Hey there! I see you're trying to get Swagger to show a multi-element array (like two Point objects) for the SourcePoints field in your Post request body, instead of the default single-element example. Let's walk through a few straightforward solutions tailored to your Springfox Swagger setup.

Background

Right now, Swagger auto-generates a single Point in the SourcePoints array example, but you want it to display multiple entries to better reflect real-world usage. We'll use your existing POJOs (CRSConversionResult.java, Point.java) and Springfox dependency to make this happen.

Solutions

1. Directly Define a Multi-Element Example with @ApiModelProperty

This is the simplest approach—just add the @ApiModelProperty annotation to the sourcePoints field in your CRSConversionResult class, and hardcode a JSON array with multiple Point objects as the example.

Update your CRSConversionResult.java like this:

import io.swagger.annotations.ApiModelProperty;
import java.util.List;

public class CRSConversionResult {
    // Your other fields here...

    @ApiModelProperty(
        value = "Collection of source points",
        example = "[{\"x\": 105.2, \"y\": 30.7}, {\"x\": 106.5, \"y\": 31.1}]"
    )
    private List<Point> sourcePoints;

    // Getters and setters...
}

Once you restart your app, Swagger will render exactly the multi-element array you specified in the example attribute.

2. Use Structured Examples with @ApiExamples (For Multiple Scenarios)

If you ever need to show multiple different examples for the same field, use Springfox's @ApiExamples and @ExampleProperty annotations instead. This keeps things structured instead of using raw JSON strings.

Here's how to implement it:

import springfox.documentation.annotations.ApiExample;
import springfox.documentation.annotations.ApiExamples;
import java.util.List;

public class CRSConversionResult {
    // Your other fields here...

    @ApiExamples({
        @ApiExample(
            value = {
                @ExampleProperty(
                    value = "[{\"x\": 105.2, \"y\": 30.7}, {\"x\": 106.5, \"y\": 31.1}]",
                    mediaType = "application/json"
                )
            }
        )
    })
    private List<Point> sourcePoints;

    // Getters and setters...
}

This is great if you want to provide multiple example payloads later, but for your current need, the first method is quicker.

3. Global Configuration (Apply to All Array Fields)

If you want every array in your Swagger docs to show multiple elements by default, you can set this up globally in your Swagger config class. This saves you from annotating every array field individually.

Create or update your SwaggerConfig.java:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.schema.AlternateTypeRule;
import springfox.documentation.schema.AlternateTypeRules;
import springfox.documentation.schema.example.Example;
import springfox.documentation.service.ParameterContext;
import springfox.documentation.schema.AbstractSerializableParameter;

import java.util.Collections;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("your.controller.package.here")) // Replace with your controller package
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
                // Add global rule for array examples
                .alternateTypeRules(
                    AlternateTypeRules.newRule(
                        typeResolver.resolve(List.class, Point.class),
                        typeResolver.resolve(List.class, Point.class),
                        new MultiElementArrayExample(2) // Show 2 elements by default
                    )
                );
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
                "Your API Documentation",
                "Description of your API endpoints",
                "1.0",
                "Terms of Service URL",
                new Contact("Your Name", "Your Website", "your.email@example.com"),
                "License Name",
                "License URL",
                Collections.emptyList()
        );
    }

    // Custom class to generate multi-element array examples
    private static class MultiElementArrayExample extends AbstractSerializableParameter {
        private final int elementCount;

        public MultiElementArrayExample(int elementCount) {
            this.elementCount = elementCount;
        }

        @Override
        public void apply(ParameterContext context) {
            context.parameterBuilder()
                    .examples(Example.builder()
                            .example(buildArrayExample())
                            .build());
        }

        private String buildArrayExample() {
            StringBuilder exampleBuilder = new StringBuilder("[");
            for (int i = 0; i < elementCount; i++) {
                exampleBuilder.append(String.format("{\"x\": %.1f, \"y\": %.1f}", 100.0 + i*5, 30.0 + i*0.5));
                if (i < elementCount - 1) {
                    exampleBuilder.append(", ");
                }
            }
            exampleBuilder.append("]");
            return exampleBuilder.toString();
        }
    }
}

This will make every List<Point> field in your API docs show 2 elements by default. Adjust the elementCount value if you want more examples.

Verify the Fix

After making any of these changes, restart your Spring Boot application and head to your Swagger UI (usually http://localhost:8080/swagger-ui.html). Find your Post endpoint, check the request body example, and you'll see SourcePoints now has multiple Point objects!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 13:48:15