将列表发送到 spring mvc - @requestBody

send List to spring mvc - @requestBody

我使用 Spring 和 JQuery 作为基础项目,我正在尝试将列表发送到服务器:

我在前端的数据(FormData):

photos[0].title: t1
photos[0].order: 100
photos[0].mimeType: mt1
photos[0].thumpnailMimeType: tmt1
photos[0].height: 101
photos[0].width: 103
photos[0].byteSize: 200
photos[0].thumpnailByteSize: 300
photos[0].relPath: rp1
photos[0].thumpnailRelPath: trp1

我也发送父对象的 url id

在spring中:

@RequestMapping(value = "/create/{id}", method = RequestMethod.POST)
public String addPhoto(@PathVariable Long id, @RequestBody List<PhotoDto> photos, HttpServletRequest req, HttpServletResponse response) {
    
    try {
        
        GalleryDto gallery = galleryApplicationService.get(id);
        
        // ...

        return "ok";
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

照片对象是:

private String title;
private Integer order;
private String mimeType;
private String thumpnailMimeType;
private Integer height;
private Integer width;
private Long byteSize;
private Long thumpnailByteSize;
private String relPath;
private String thumpnailRelPath;

private GalleryDto gallery;

我的错误是:Bad Request 400

  1. 我改成Jquery ajax:(values是对象数组)
$.ajax({
    url: http:\...,
    type: ...,
    data: JSON.stringify( values ),
    contentType: "application/json",
    dataType: "json",
    ...
});
  1. 我也为服务器更改了 FormDate
[
    {   
        title: t1
        order: 100
        mimeType: mt1
        thumpnailMimeType: tmt1
        height: 101
        width: 103
        byteSize: 200
        thumpnailByteSize: 300
        relPath: rp1
        thumpnailRelPath: trp1
    },
]
  1. 添加依赖jackson :
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.9</version>
</dependency>
  1. consumesproduces 添加到 @RequestMapping:
@RequestMapping(value = "/create/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)