Spring Rest JSON Binding

16,128

Solution 1

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?

Solution 2

This is probably not the main problem, but your UserContext bean would not work as is, if it only has private fields. There are multiple ways to resolve this; from making fields public, to adding @JsonProperty for each, or just changing minimum visibility jackson uses for detecting property fields (@JsonAutoDetect annotation).

But with empty JSON, this should not give problems; and if there was an issue, you should see different kind of error/exception (I assume).

Share:
16,128
Sri
Author by

Sri

Make stuff. Build things. - https://srirangan.net

Updated on June 12, 2022

Comments

  • Sri
    Sri almost 2 years

    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!