简体   繁体   English

SpringMVC控制器的JSON响应无效

[英]JSON response from SpringMVC controller is not working

I want to response JSON object or array from Spring MVC controller. 我想从Spring MVC控制器响应JSON对象或数组。 From these two beingjavaguys and mkyoung tutorial, i tried. 从这两个是javaguysmkyoung教程,我试过。 I could success only in when the response is string. 只有当响应是字符串时我才能成功。 But when the response is in object or in list, it doesn't work for me. 但是当响应在对象或列表中时,它对我不起作用。

//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;
}

Output is: 输出是: 在此输入图像描述

But the problem is in it, 但问题在于它,

@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;
    }

It shows, 表明,

HTTP ERROR 406

Problem accessing /mkyoung.html. Reason:

    Not Acceptable

But if i change it toString() , It works but not with right output 但是如果我将它改为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();

}

在此输入图像描述

But i need JSON object or array of object as response. 但我需要JSON对象或对象数组作为响应。 What is the probelm ? 什么是probelm? I have added jsckson dependency in my pom.xml 我在我的pom.xml添加了jsckson依赖项

<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.10</version>
    </dependency>

UPDATE: Now i am sending request from angular js by adding 更新:现在我通过添加来发送角度js的请求

headers: {
                "Content-Type": "application/json"
            }

My dispatcher-servlet.xml 我的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>

As Sotirios Delimanolis's Answer suggesion. 作为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");
        });

But it shows same error. 但它显示相同的错误。 在此输入图像描述

Also add jackson core 还添加杰克逊核心

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

For List use method return type Object 对于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;
}

Given @ResponseBody with a POJO type return type, a default MVC configuration with @EnableWebMvc or <mvc:annotation-driven /> , and Jackson on the classpath, Spring will try to serialize the POJO to JSON and write it to the response body. 给定带有POJO类型返回类型的@ResponseBody ,带有@EnableWebMvc<mvc:annotation-driven />的默认MVC配置,以及类路径上的Jackson,Spring将尝试将POJO序列化为JSON并将其写入响应主体。

Since it's writing JSON, it's going to attempt to write application/json as the Content-type header. 由于它正在编写JSON,它将尝试将application/json编写为Content-type头。 The HTTP specification requires that the server only responds with content types that are part of the Accept header in the request. HTTP规范要求服务器仅响应作为请求中Accept标头一部分的内容类型。

It seems you're sending your request with an inappropriate Accept header that doesn't contain application/json . 您似乎正在使用不包含application/json的不合适的Accept标头发送您的请求。 Fix that. 修复它。


Note that you are sending your request to 请注意,您要将请求发送给

/mkyoung.html

Spring, by default, uses content negotiation based on some extensions. 默认情况下,Spring使用基于某些扩展的内容协商。 For example, with .html , Spring will think the request should produces text/html content, which is contrary to the application/json you want to send. 例如,使用.html ,Spring会认为请求应该生成text/html内容,这与您要发送的application/json相反。

Since your handler is already mapped to 由于您的处理程序已映射到

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

just send the request to the corresponding URL, ending in /mkyoung . 只需将请求发送到相应的URL,以/mkyoung (Get rid of the .html extension.) (摆脱.html扩展名。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM