[java] JSON post to Spring Controller

Hi I am starting with Web Services in Spring, so I am trying to develop small application in Spring + JSON + Hibernate. I have some problem with HTTP-POST. I created a method:

@RequestMapping(value="/workers/addNewWorker", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public String addNewWorker(@RequestBody Test test) throws Exception {
    String name = test.name;
    return name;
}

And my model Test looks like:

public class Test implements Serializable {

private static final long serialVersionUID = -1764970284520387975L;
public String name;

public Test() {
}
}

By POSTMAN I am sending simply JSON {"name":"testName"} and I always get error;

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

I imported Jackson library. My GET methods works fine. I don't know what I'm doing wrong. I am grateful for any suggestions.

This question is related to java json spring spring-mvc

The answer is


Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.


You need to include the getters and setters for all the fields that have been defined in the model Test class --

public class Test implements Serializable {

    private static final long serialVersionUID = -1764970284520387975L;

    public String name;

    public Test() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Do the following thing if you want to use json as a http request and response. So we need to make changes in [context].xml

<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonMessageConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>   

MappingJackson2HttpMessageConverter to the RequestMappingHandlerAdapter messageConverters so that Jackson API kicks in and converts JSON to Java Beans and vice versa. By having this configuration, we will be using JSON in request body and we will receive JSON data in the response.

I am also providing small code snippet for controller part:

    @RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)

    public @ResponseBody Employee getDummyEmployee() {
    logger.info("Start getDummyEmployee");
    Employee emp = new Employee();
    emp.setId(9999);
    emp.setName("Dummy");
    emp.setCreatedDate(new Date());
    empData.put(9999, emp);
    return emp;
}

So in above code emp object will directly convert into json as a response. same will happen for post also.


see here

The consumable media types of the mapped request, narrowing the primary mapping.

the producer is used to narrow the primary mapping, you send request should specify the exact header to match it.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)