Spring MVC不接受json请求体

时间:2014-05-14 14:55:23

标签: json spring spring-mvc

我是一个春天的新手,我试图将一个json对象传递给spring mvc:

POJO代表json

public class City implements Serializable{

    private String id;  
    private Map<String,Map<String,String>> translates;
    private Map<String,String> providers;

    public City(){}

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

    public Map<String, Map<String, String>> getTranslates() {
        return translates;
    }

    public void setTranslates(Map<String, Map<String, String>> translates) {
        this.translates = translates;
    }

    public Map<String, String> getProviders() {
        return providers;
    }

    public void setProviders(Map<String, String> providers) {
        this.providers = providers;
    }

}

控制器

@RequestMapping(value="/insert",method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody City insert(@RequestBody City city){
    return city; // JUST FOR TEST
}

的pom.xml

...
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.0-rc2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.0-rc2</version>
</dependency>
....

如果我尝试使用那个Json

{
    "id": "Test",
    "translates": {
        "it": {
            "country": "testCountryIT",
            "city": "testCityIT"
        },
        "en": {
            "country": "testCountryEn",
            "city": "testCityEn"
        }
    },
    "providers": {
        "prov1": "YYY",
        "prov2": "XXX"
    }
}

我检索到该错误消息:

"NetworkError: 415 Unsupported Media Type

可能是什么问题?

谢谢!

1 个答案:

答案 0 :(得分:2)

您似乎没有在请求中发送Content-Type标头,其值为application/json。您的请求需要包含该标头,以便Spring可以1)使用适当的HttpMessageConverter和2)使用@RequestMapping方法处理请求。