我有兩個類結合嵌套JSON使用傑克遜變換器
到@RequestBody對象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對象與兒童對象的方式。有人可以幫我在這裏。此外,有建議使用的
private ArrayList<HashMap<String, Child>> children = new ArrayList<HashMap<String, Child>>();
代替
private ArrayList<Child> children = new ArrayList<Child>();
謝謝。
由於某種原因,我想出了一個問題,我使用的其他客戶端使事情變得更糟。現在正在工作。這是輸入json的問題。不是應用程序本身。謝謝你們的幫助...... – user845730