简体   繁体   中英

Spring MVC 4.1.x RestFul Service throwing Not Acceptable for Json

I have made a Rest Service using Spring MVC4.1.X, but whenever I try to return Json o/p to browser iam getting the following error

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

Iam using @Response body for auto conversion of a Java pojo into JSON objects. I have tried almost all the solution given on stackoverflow .

my controller class 
package com.spring.rest.ambulance;

import java.io.IOException;

import net.sf.json.JSONObject;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.spring.dao.AmbulanceDAO;
import com.spring.dao.AmbulanceDAOImpl;
import com.spring.model.Ambulance;


@RestController
@RequestMapping("/Ambulance")
public class AmbulanceRestController {
    @Autowired
    private AmbulanceDAO ambulanceDAO;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public @ResponseBody String getAllUsers(ModelMap model) {
        String jsonData = "[{\"id\":\"3253123\",\"firstname\":\"Chris\",\"lastname\":\"Johnson\",\"address\":\"211, Geoffrey Drive\",\"city\":\"Newark\",\"phone\":\"999-888-6666\",\"email\":\"chrisj@yahoo.com\"},{\"id\":\"67643837\",\"firstname\":\"Bill\",\"lastname\":\"Derkson\",\"address\":\"201, Sleepy Hollow Drive\",\"city\":\"Newark\",\"phone\":\"999-777-2222\",\"email\":\"billd@gmail.com\"}]";
        return jsonData;
    }

    @RequestMapping(value = "/{id}")
    public @ResponseBody Ambulance getAmbulanceProviders(ModelMap model,
            @PathVariable("id") int Id) {
        String jsonData = null ;
        Ambulance ambulance = ambulanceDAO.getById(Id);
        ObjectMapper objmapper = new ObjectMapper();
        try {
             jsonData = objmapper.writeValueAsString(ambulance);
            //System.out.println(objmapper.writeValueAsString(ambulance));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ambulance;
    }

Entity being returned 
package com.spring.model;

import org.codehaus.jackson.map.ObjectMapper;

public class Ambulance {

    private int ID;
    private String vehicleNumber;
    private String ambulanceType;
    private String ambulanceProviderName;
    /**
     * @return the iD
     */
    public int getID() {

        return ID;
    }

    /**
     * @param iD
     *            the iD to set
     */
    public void setID(int iD) {
        ID = iD;
    }


    /**
     * @return the vehicleNumber
     */
    public String getVehicleNumber() {
        return vehicleNumber;
    }

    /**
     * @param vehicleNumber
     *            the vehicleNumber to set
     */
    public void setVehicleNumber(String vehicleNumber) {
        this.vehicleNumber = vehicleNumber;
    }

    /**
     * @return the ambulanceType
     */
    public String getAmbulanceType() {
        return ambulanceType;
    }

    /**
     * @param ambulanceType
     *            the ambulanceType to set
     */
    public void setAmbulanceType(String ambulanceType) {
        this.ambulanceType = ambulanceType;
    }

    /**
     * @return the ambulanceProviderName
     */
    public String getAmbulanceProviderName() {
        return ambulanceProviderName;
    }

    /**
     * @param ambulanceProviderName
     *            the ambulanceProviderName to set
     */
    public void setAmbulanceProviderName(String ambulanceProviderName) {
        this.ambulanceProviderName = ambulanceProviderName;
    }
    @Override
    public String toString() {
        return "{ID="+ID+",AmbulanceProvderName="+ambulanceProviderName+",AmbulanceType="+ambulanceType+",VehicleNumber="+vehicleNumber+"}";
    }

}

    DAO Ambulance get by Id
    public Ambulance getById(int id) {
        // TODO Auto-generated method stub
        Ambulance ambulance = new Ambulance(); 
    /*  JdbcTemplate jdbcTemplate =  new JdbcTemplate();
        System.out.println(dataSource);
        jdbcTemplate.setDataSource(dataSource);*/
        System.out.println(jdbcTemplate.getDataSource());
        String sql = "SELECT * FROM AMBULANCE WHERE AMBULANCEID = ?";
        ambulance = (Ambulance)jdbcTemplate.queryForObject(sql,new Object[] { id }, new AmbulanceRowMapper());


        return ambulance;
    }


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>SpringWebAppRestServices</groupId>
    <artifactId>SpringWebAppRestServices</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.1.4.RELEASE</version>
        </dependency>

    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Originally this issue occurs when the request sends an accept header that differs from the response's content-type. I don't know if this is the case, there's not enough source provided.

However, another a bit more trickier situation when the same error occurs is when the framework is not able to convert the response to an appropriate representation, eg on account of bad getters/setters or missing dependencies.

In the code you posted I see an issue with your dependencies. Spring 4.1 needs minimum Jackson 2.1 , and in the version Jackson 2 and above a package change occurred from codehaus to fasterxml . Replace the two of your Jackson dependencies with the following one

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

or better yet go for a newer version. Single dependency is enough it will transitively pull com.fasterxml.jackson.core:jackson-annotations:jar and com.fasterxml.jackson.core:jackson-core:jar

I think you might have to ensure that your Request is having the following in your header:

GET 
Accept: application/json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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