【发布时间】:2017-12-17 01:10:14
【问题描述】:
我收到了这个错误。我尝试将此代码添加到属性中:“spring.jackson.deserialization.accept-single-value-as-array=true”但我无法解决这个问题?
org.springframework.http.converter.HttpMessageNotReadableException:JSON 解析错误:无法从 START_OBJECT 令牌中反序列化 java.util.ArrayList 的实例;嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException:无法从 START_OBJECT 令牌中反序列化 java.util.ArrayList 的实例 在 [来源:java.io.PushbackInputStream@2e64d73;行:1,列:145](通过引用链:com.test.mobil.viewmodel.CompanyViewModel ["customerList"])
客户视图模型
public class CustomerViewModel {
private String name;
private String surname;
private int birthDate;
public CustomerViewModel(){}
public CustomerViewModel(String name, String surname, int birthDate) {
this.name = name;
this.surname = surname;
this.birthDate = birthDate;
}
}
CompanyViewModel
public class CompanyViewModel {
private String company;
private List<CustomerViewModel> customerList;
public CompanyViewModel(){}
public CompanyViewModel(String company, List<CustomerViewModel> customerList) {
this.company = company;
this.customerList = customerList;
}
}
客户控制器
@Controller
public class CustomerController {
@PostMapping("/customer")
public void setCustomer(@RequestBody CompanyViewModel companyViewModel){
System.out.println(companyViewModel);
}
}
JSON
page = {
company: "Facebook",
customerList = [
{
name: "Test1",
surname: "Test2",
birthDate: 1987
},
{
name: "Test3",
surname: "Test4",
birthDate: 1988
}
]
}
【问题讨论】:
-
你的 JSON 好像错了!!将
customerList =替换为customerList : -
除非您已正确配置使用的
ObjectMapper,否则您还必须将 getter/setter 添加到您希望使其可序列化/可反序列化的对象的私有字段中。 -
您应该将您的 JSON 示例更改为
customerList实际上只是一个 JSON 对象(而不是 JSON 数组)以匹配您的异常。 -
您实际发送的是什么 JSON。您应该发送:
{ company: "Facebook", customerList = [ { name: "Test1", surname: "Test2", birthDate: 1987 }, { name: "Test3", surname: "Test4", birthDate: 1988 } ] }也不要使用page=,请使用customerList:而不是customerList=
标签: java arrays json spring spring-boot