在请求中将发布参数映射到DTO

Mar*_*cak 3 java spring spring-mvc java-8 spring-boot

在我的Spring启动应用程序中,我将POST使用以下(例如)params 发送数据:

data: {
        'title': 'title',
        'tags': [ 'one', 'two' ],
        'latitude': 20,
        'longitude': 20,
        'files': [ ], // this comes from a file input and shall be handled as multipart file
    }
Run Code Online (Sandbox Code Playgroud)

在我的@Controller身上:

@RequestMapping(
        value = "/new/upload", method = RequestMethod.POST,
        produces = BaseController.MIME_JSON, consumes = BaseController.MIME_JSON
)
public @ResponseBody HttpResponse performSpotUpload(final SpotDTO spot) {
// ...
}
Run Code Online (Sandbox Code Playgroud)

哪里SpotDTO是非POJO全班getterssetters.

public class SpotDTO implements DataTransferObject {

    @JsonProperty("title")
    private String title;

    @JsonProperty("tags")
    private String[] tags;

    @JsonProperty("latitude")
    private double latitude;

    @JsonProperty("longitude")
    private double longitude;

    @JsonProperty("files")
    private MultipartFile[] multipartFiles;

    // all getters and setters
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,所有字段都是null在我收到请求时.Spring无法将参数映射到我的DTO对象.

我想我错过了一些配置,但我不知道哪一个.


只需在DTO类上设置字段访问器即可解决其他类似问题.这对我不起作用.

另外我注意到如果我在方法中指定每个参数:

@RequestParam("title") final String title,
Run Code Online (Sandbox Code Playgroud)

请求甚至没有达到该方法.我可以在LoggingInterceptor preHandle方法中看到传入的请求,但没有任何内容postHandle.一个404发回响应.

Bri*_*ian 5

我想你只是缺少@RequestBody参数的注释:

@RequestMapping(
        value = "/new/upload", method = RequestMethod.POST,
        produces = BaseController.MIME_JSON, consumes = BaseController.MIME_JSON
)
public @ResponseBody HttpResponse performSpotUpload(@RequestBody final SpotDTO spot) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)