Spring不解析@RequestBody?

时间:2017-07-12 14:27:51

标签: java arrays json spring spring-boot

我收到了这个错误。我尝试添加属性这段代码:" 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; line:1,column:145](通过参考链:com.test.mobil.viewmodel.CompanyViewModel [" customerList"])

CustomerViewModel

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;
}
}

CustomerController

@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
        }

    ]
}

2 个答案:

答案 0 :(得分:-1)

您误解了问题:数组无法反序列化,因为它无效JSON!您的=位于customerList = [,如下所示:

JsonMappingException: Can not deserialize instance of java.util.ArrayList
                          out of START_OBJECT token
    at [Source: java.io.PushbackInputStream@2e64d73; line: 1, column: 145]
        (through reference chain: com.test.mobil.viewmodel.CompanyViewModel ["customerList"])

答案 1 :(得分:-1)

非常感谢你们。我检查了前端的JSON值,我看到了这样。我的JSON不包括Array,因为Angular误导了我。 我将列表更改为地图,问题已解决!

{  
"customer":{  
  "name":"name1",
  "surname":"sur1",
  "company":"firm",
  "address":"adres",
  "phone":"tel",
  "fax":"faxx",
  "type":"real",
  "taxNo":"2398"
},
"products":{  
  "0":{  
     "company":"es",
     "product":"a",
     "detail":"a",
     "value":2
  },
  "1":{  
     "company":"we",
     "product":"qwe",
     "detail":"qwe",
     "value":1
  }
},
}