【发布时间】:2011-07-15 03:39:10
【问题描述】:
我有两节课
public class Parent {
private String name;
private int age;
private ArrayList<Child> children = new ArrayList<Child>();
//Setters and getter to follow..
}
public Class Child {
private String name;
private int age;
}
Spring 配置包括:
<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter" />
</list>
</property>
</bean>
控制器如下所示:
@RequestMapping(value = "/parents",
method = RequestMethod.POST,
headers="Content-Type=application/json")
public @ResponseBody Parent add(@RequestBody Parent parent, Model model) {
logger.debug("Received request to add a parent");
Parent tempParent = parentService.add(parent); // This will persist the parent object to the DB.. (Helper class)
return tempContract;
}
在正常情况下,它应该将传入的json绑定到Parent,并在响应中将Parent作为Json返回。它给了我一个例外:“客户端发送的请求在语法上不正确。”使用以下输入 Json:
{
"name" : "foo",
"age" : "45",
"children" : [
{
"name" : "bar",
"age" : "15""
},
{
"name" : "baz",
"age" : "10""
}
]
}
因此尝试更改 json,它可以很好地使用以下格式绑定 @RequestBody 和 @ResponseBody:
{
"name" : "foo",
"age" : "45",
"children" : []
}
和
{
"name" : "foo",
"age" : "45",
"children" : [
{}
]
}
所以我假设实际的子类或我传递 Json 对象 wrt Child 对象的方式有问题。有人可以帮我吗。另外,是否建议使用
private ArrayList<HashMap<String, Child>> children = new ArrayList<HashMap<String, Child>>();
而不是
private ArrayList<Child> children = new ArrayList<Child>();
谢谢。
【问题讨论】:
标签: java json spring binding jackson