无法将数组传递给Spring boot Java

问题描述 投票:0回答:2

我正在尝试向Sprin引导发送POST请求,并在正文中列出自定义对象。我在请求正文中的JSON是这样的:

[{"name":"name1","icon":"icon1"},
{"name":"name2","icon":"icon2"},
{"name":"name3","icon":"icon3"}]

我收到此错误

Cannot construct instance of `io.wedaily.topics.models.Topic` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

我的控制器:

@PostMapping
public void createTopics(@RequestBody List<Topic> topics) {
    System.out.println(topics);
}

我的主题模型:

public class Topic {

    private Long id;
    private String name;
    private String icon;
    private Date createdAt;
// Constructor
// Getters
// Setters
}
java spring-boot spring-restcontroller
2个回答
4
投票

该异常是非常明确的,它会告诉您发生了什么。 Jackson需要为要反序列化的每个字段定义一个默认的,无参数的构造函数,该构造函数需要使用getter和setter进行定义,或者,您需要一个带有Jackson注释的构造函数,以告知其如何将json映射到构造函数中。

只需修改您的主题类,以包括如下所示的默认构造函数。 (如果您使用lombok用@Data注释您的班级,也可以做到这一点)

public class Topic {
 private Long id; 
 private String name; 
 private String icon; 
 private Date createdAt; 

 public Topic(){
 }

 // Other all args constructor
 // Getters
 // Setters 
}

0
投票

您的应用程序需要一个模型类,Jackson可以将您的帖子数据映射到某种对象,然后您可以创建该对象的列表。

就像您要发送的帖子是>

[{"name":"name1","icon":"icon1"},
{"name":"name2","icon":"icon2"},
{"name":"name3","icon":"icon3"}]

所以您的模型类会像

public class mapModel { 
    private String name;
    private String icon;

    public String getName(){return this.name;}
    public void setName(String name){this.name  = name;}

    public String getIcon(){return this.icon;}
    public void setIcon(String icon){this.icon  = icon;}
}

并且您的postMapping控制器将如下所示:>

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import com.doc.autobuild.autobuild.model.mapModel;

@RestController
public class postMappingExample{
    @PostMapping("/reqPost")
    public ResponseEntity<HttpStatus> postController(@RequestBody List<mapModel> bodyParamList){
        for(mapModel mm : bodyParamList){System.out.println(mm.getName());}
        return ResponseEntity.ok(HttpStatus.OK);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.