将JSON数组发布到Spring控制器时出现400 Bad Request

时间:2013-05-14 02:44:04

标签: rest spring-mvc http-post

我成功地将一个简单的JSON对象发送到spring框架Controller

curl -v -H  "Content-Type: application/json" -H "Accept: application/json"  -d '{"lastName":"Smith","firstName":"John"}' http://localhost:8080/WebServices02/aura/testJsonArray

但是,当我发送带有嵌入式数组的JSON对象时

curl -v -H  "Content-Type: application/json" -H "Accept: application/json"  -d '{"lastName":"Smith","pals":[{"name":"Billy"}],"firstName":"John"}' http://localhost:8080/WebServices02/aura/testJsonArray

我收到错误400'客户端发送的请求语法不正确()。'

我的控制器是

@Controller
@RequestMapping(value="/aura")
public class AuraController {

@RequestMapping(value = "/testJsonArray", method = RequestMethod.POST,  headers = {"content-type=application/json"})
@ResponseBody
public void testJsonArray(@RequestBody  Aura aura){
    System.err.println("Called testJsonArray(): " + "Aura is " + aura.toString());
}

}

我的Aura类被定义为

import java.io.Serializable;
import java.util.List;
import org.json.JSONObject;

public class Aura implements Serializable {

public class Pal{
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


private String firstName;

private String lastName;

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

private List<Pal> pals;

public String toString(){
    return new JSONObject(this).toString();

}

public List<Pal> getPals() {
    return pals;
}

public void setPals(List<Pal> pals) {
    this.pals = pals;
}

}

我的bean(在mvc:message-converters下)是

<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>

如果有人可以帮我这个......谢谢

1 个答案:

答案 0 :(得分:1)

  

你必须在项目中包含jackson-core-asl和jackson-mapper-asl的Jackson JSON Mapper依赖项。

     

这对于将json映射到java pojo类字段是必要的。