Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Rest JSON Binding

I'm trying to create a Restful service with Spring.

A method accepts a "UserContext" object via argument i.e. @RequestBody.

The client sends the JSON object with content-type "application/json". But I get the error "HTTP/1.1 415 Unsupported Media Type".

..even when the client sends a null "{}" JSON object.

My controller:

@Controller
@RequestMapping(value = "/entityService")
class RestfulEntityService {

  @Resource
  private EntityService entityService;

  @ResponseBody
  @RequestMapping(value = "/getListOfEntities", method = RequestMethod.POST)
  public List<Entity> getListOfEntities(@RequestBody UserContext userContext) {
    System.out.println(userContext);
    return null;
  }
}

UserContext.java

public class UserContext {

    private Long userId;

    private String userName;

    private UserAddress userAddress;

    private CustomerInfo customerInfo;

}

Application context:

  <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/>
  <bean id="xmlMessageConverter"
        class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <constructor-arg ref="xstreamMarshaller"/>
    <property name="supportedMediaTypes" value="application/xml"/>
  </bean>

  <bean id="jsonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json"/>
  </bean>

  <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
      <util:list id="beanList">
        <ref bean="xmlMessageConverter" />
        <ref bean="jsonHttpMessageConverter"/>
      </util:list>
    </property>
  </bean>

  <mvc:annotation-driven/>

Struggling with this for a while. Help will be appreciated!

like image 688
Sri Avatar asked Feb 25 '23 13:02

Sri


1 Answers

Try with a Accept header in your request of application/json, based on what I see with the messageconverter samples at mvc-showcase

This is a related question: use spring mvc3 @ResponseBody had 415 Unsupported Media Type why?

like image 70
Biju Kunjummen Avatar answered Mar 04 '23 01:03

Biju Kunjummen