嵌套对象的Spring JSON数据绑定不起作用

时间:2012-08-20 15:17:55

标签: java json spring data-binding

我有以下Person类包含另一个Car

public class Person {
    private String name
    private Car car;        
    ... getter and setters
}

public class Car {
    private String manufacturer;
    ... getter and setters
}

在Javascript中,我执行以下操作:

person = new Object();
person.name = "Bob";

person.car = new Object();

car = person.car;

car.manufacturer = "Mercedes";

$.ajax({
    url: 'someurl.com',
    type: 'POST',
    data: person,
    dataType: 'json',
    ...
    complete: function() {
        ...
    }
});

使用自动绑定功能时,我收到以下错误:

功能:

public @ResponseBody Car validateCar( Car car, HttpServletRequest servletRequest){
        ...
}

错误:

org.springframework.beans.InvalidPropertyException: Invalid property 'car[manufacturer]' of bean class [com.example.Person]: Property referenced in indexed property path 'car[manufacturer]' is neither an array nor a List nor a Map; returned value was []

如何使映射工作?

btw:我的POST数据如下所示:

name: Bob
car[manufacturer]: Mercedes

字符串化为JSON,它看起来如下(我测试了它,但我没有将其字符串化)

{"name":"Bob",
 "car": {
  "manufacturer":"Mercedes"
 }
}

2 个答案:

答案 0 :(得分:0)

似乎你传入Car hash并尝试将其自动绑定到Person对象。为此,您的哈希需要看起来像人[car [制造]]]。尝试在javascript中传入你的person对象,然后将car对象拉出自动双向对象。

答案 1 :(得分:0)

我认为你在车上缺少@RequestBody:

public @ResponseBody Car validateCar( @RequestBody Car car, HttpServletRequest servletRequest)