The latest version of Spring MVC, 4.1.x, is encountering a "Not Acceptable" error while trying

After creating a Rest Service using Spring MVC4.1.X, I encountered an issue when attempting to return Json output to the browser. The error message displayed was:

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

I have utilized @ResponseBody for automatic conversion of a Java pojo into JSON objects and have attempted various solutions from Stack Overflow without success.

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\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f6959e849f859cb68f979e9999d895999b">[email protected]</a>\"},{\"id\":\"67643837\",\"firstname\":\"Bill\",\"lastname\":\"Derkson\",\"address\":\"201, Sleepy Hollow Drive\",\"city\":\"Newark\",\"phone\":\"999-777-2222\",\"email\":\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5a7aca9a9a185a2a8a4aca9eba6aaa8">[email protected]</a>\"}]";
        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);

        } catch (IOException e) {
            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;

    //getters and setters omitted

}

DAO Ambulance getById

public Ambulance getById(int id) {
        Ambulance ambulance = new Ambulance();  
        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
<!-- POM file content -->

Answer №1

When a request sends an accept header that doesn't match the response's content-type, it can lead to this issue. Without enough information provided, it's hard to determine if this is causing the problem.

Another more complex scenario where this error might occur is when the framework is unable to convert the response into the correct representation due to issues like improper getters/setters or missing dependencies.

In the code snippet you shared, there seems to be a problem with your dependencies. Spring 4.1 requires at least Jackson 2.1. For versions of Jackson 2 and higher, there was a package change from codehaus to fasterxml. You should replace your existing Jackson dependencies with the following:

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

Alternatively, consider upgrading to a newer version. A single dependency is sufficient as it will automatically include

com.fasterxml.jackson.core:jackson-annotations:jar
and
com.fasterxml.jackson.core:jackson-core:jar
transitively.

Answer №2

It's important to make sure that your Request includes the following headers:

GET 
Accept: application/json

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to emphasize a particular <li> element?

Currently, I am delving into the world of React and facing a challenge. I have been trying to solve the issue below: When fetching some JSON data, it appears in this format: [ { "answerOptions": [ "Answer A", "Answer B", ...

Tips for building a versatile fetch function that can be reused for various JSON formats within a React application

Using the fetch method in various components: fetch(url) .then(result => { if (!result.ok) { throw new Error("HTTP error " + result.status) } return result.json() }) .then(result => { ...

Tips for preserving axois GET response as a JSON object or in its original form upon arrival

export class LoadProfile extends Component { state = { data: '' } componentDidMount() { axios({ url: 'http://localhost:8080/profile/all', method: 'GET', responseType: 'json', ...

What is causing the difficulty in accessing the 'query' feature within the API, and why is the question bank failing to display?

Just wanted to mention that I am still learning about class based components, setState, and other concepts in async JS like axios. Below is a very basic example of what I can currently do. This is App.js: import Questions from './components/Ques ...

I am struggling to figure out the best way to save JSON data retrieved from an API request in a Node.js Express server, and then efficiently send it to a React Native client

My Node.js server is up and running with an app.js file structured like this: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-pars ...

Is there a way to retrieve data from my JSON file located in the public folder within Next.js 13.3?

My current challenge involves retrieving JSON data from the public folder. async function fetchData() { try { const response = await fetch('/data.json'); const jsonData = await response.json(); return jsonData; } catch (error) { ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

Issue with optimizing in Webpack 4

It's past 2am and I find myself going crazy trying to identify an error. The console keeps repeating the message: "Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." I've attempted modifyi ...

What is the most effective way to import a substantial static array in React for utilization in a select field?

The scenario is quite straightforward. I currently have a single array containing over 2500 strings of company names, saved locally in the project as a JSON file within a subdirectory under src. To access this data in my component, I am importing the JSON ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

Having difficulty displaying JSON data in a react component

I am currently working on parsing JSON data retrieved from an Ajax call in order to display it in a table using the React DataTable component. However, I have encountered a problem while trying to store the data in a state variable using the setState metho ...

I keep encountering a "map is not a function" error while working with React JS

I am attempting to retrieve and display data from a MySQL database using Spring Boot and React JS in a table format. However, I am encountering an error while trying to display the information. componentDidMount(){ const currentUser = AuthService.g ...

Switching XML to JSON using React.js

Currently, I am in the process of developing an application with a requirement to retrieve data from a web API that provides XML responses. However, my objective is to obtain this information in JSON format, but unfortunately, the API does not offer suppor ...

Looking to locate or track duplicate values within a multi-dimensional array?

In a multidimensional array, I am looking to detect and count duplicates. If duplicates are found, an alert should be triggered. Arr =[[2,"sk"],[3,"df"],[7,"uz"],[3,"df"],[7,"gh"]] Suggestions: One way to ...

What is the best way to add additional buttons to my React App after the initial button has been clicked?

Currently, I am in the process of developing a CSV file loader that converts data into JSON format. The loader will consist of three buttons: 1. The first button allows me to select a file from my computer and load the CSV data for conversion to JSON. 2. ...

Combining Spring Boot with React Using Material UI Design

Currently in the process of setting up a Spring Boot project (Prototype) using React and Material UI. To kick things off, I utilized this tutorial to successfully get Spring Boot functioning with React. Moving on to implementing Material UI, I followed st ...

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

Updating the value of a different key within the same object using React Formik's setFieldValue方法

My objective is to automatically select a value in an option select when the onChange event occurs, and then use setFieldValue to set values for 2 Fields with key-value pairs within the same object. The issue I'm facing: Why does calling setFieldValu ...

Utilizing React to dynamically load JSON data and render a component

I am currently facing a challenge in rendering a React component that includes data fetched from a JSON using the fetch() method. Although the API call is successful, I am experiencing difficulties in displaying the retrieved data. Below is the code snip ...

Accessing a specific data point from a Rest Api with React JS

How can I extract the value '00000000000000000000000000000000' that comes after clusters in the links->href in a Rest Api response? [{ "analysisUnits": [ { "links": [ { "href": "http://127.0. ...