SpringMVC控制器的JSON响应无效

时间:2015-06-03 15:37:55

标签: java json spring-mvc controller

我想从Spring MVC控制器响应JSON对象或数组。从这两个beingjavaguysmkyoung教程中,我试过了。 只有当响应是字符串时我才能成功。但是当响应在对象或列表中时,它对我不起作用。

//It works
@RequestMapping(value = "/angular", method = RequestMethod.GET)
public @ResponseBody String getAllProfiles( ModelMap model ) {
String jsonData = "[{\"firstname\":\"ajitesh\",\"lastname\":\"kumar\",\"address\":\"211/20-B,mgstreet\",\"city\":\"hyderabad\",\"phone\":\"999-888-6666\"},{\"firstname\":\"nidhi\",\"lastname\":\"rai\",\"address\":\"201,mgstreet\",\"city\":\"hyderabad\",\"phone\":\"999-876-5432\"}]";
return jsonData;
}

输出是: enter image description here

但问题在于它,

@RequestMapping(value = "mkyoung", method = RequestMethod.GET)
    public @ResponseBody Shop getShopInJSON() {

        Shop shop = new Shop();
        shop.setName("G");
        shop.setStaffName(new String[] { "mkyong1", "mkyong2" });
        return shop;
    }

显示,

HTTP ERROR 406

Problem accessing /mkyoung.html. Reason:

    Not Acceptable

但如果我改变它toString(), 它有效,但没有正确的输出

@RequestMapping(value = "mkyoung", method = RequestMethod.GET)
public @ResponseBody String getShopInJSON() {

    Shop shop = new Shop();
    shop.setName("G");
    shop.setStaffName(new String[] { "mkyong1", "mkyong2" });
    return shop.toString();

}

enter image description here

但我需要JSON对象或对象数组作为响应。什么是probelm?我在pom.xml

中添加了jsckson依赖项
<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.10</version>
    </dependency>

更新: 现在我通过添加

从角度js发送请求
headers: {
                "Content-Type": "application/json"
            }

我的dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <mvc:annotation-driven />

    <context:component-scan base-package="com.sublime.np.controller" />

    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/defs/general.xml</value>
            </list>
        </property>
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.tiles3.TilesView" />
    </bean>

</beans>

作为Sotirios Delimanolis的答案建议。

$http({
            url: '/mkyoung.html',
            method: 'GET',
            data: id,
            headers: {
                "Content-Type": "application/json"
            }
            }).success(function(response){
                $scope.response = response;
                console.log($scope.response);
               /*  $scope.hideTable = false;
                $scope.hideButton  = false ; */
            }).error(function(error){
                $scope.response = error;
                console.log("Failed");
        });

但它显示同样的错误。 enter image description here

2 个答案:

答案 0 :(得分:2)

还添加杰克逊核心

<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>2.5.1</version>
</dependency>

对于List使用方法返回类型Object

@RequestMapping(value = "mkyoung", method = RequestMethod.GET)
    public @ResponseBody Object getShopInJSON() {

        Shop shop = new Shop();
        shop.setName("G");
        shop.setStaffName(new String[] { "mkyong1", "mkyong2" });
        Shop shop1 = new Shop();
        shop1.setName("G1");
        shop1.setStaffName(new String[] { "mkyong1", "mkyong2" });
        List<Shop> shops = new ArrayList<Shop>();
        shops.add(shop1);
        shops.add(shop);
        return shops;
}

答案 1 :(得分:1)

给定@ResponseBody带有POJO类型的返回类型,带有@EnableWebMvc<mvc:annotation-driven />的默认MVC配置,以及类路径上的Jackson,Spring将尝试将POJO序列化为JSON并写入它是响应机构。

由于它正在编写JSON,它将尝试将application/json写为Content-type标头。 HTTP规范要求服务器仅响应作为请求中Accept标头一部分的内容类型。

您似乎发送的请求中包含的Accept标头不适合application/json。解决了这个问题。

请注意,您要将请求发送至

/mkyoung.html

默认情况下,Spring使用基于某些扩展的内容协商。例如,对于.html,Spring会认为请求应生成text/html内容,这与您要发送的application/json相反。

由于您的处理程序已映射到

@RequestMapping(value = "/mkyoung", method = RequestMethod.GET)

只需将请求发送到相应的网址,以/mkyoung结尾。 (摆脱.html扩展名。)