2011-04-11 65 views
3

我试图用Spring创建一个Restful服务。Spring Rest JSON绑定

一个方法通过参数接受一个“UserContext”对象,即@RequestBody。

客户端发送内容类型为“application/json”的JSON对象。但是我收到错误“HTTP/1.1 415 Unsupported Media Type”。

......即使客户端发送空的“{}”JSON对象。

我的控制器:

@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; 

} 

应用程序上下文:

<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/> 

与此挣扎了一会儿。帮助将不胜感激!

回答

0

确保你有你的类路径杰克逊库,如果你正在使用maven,定义在你的pom.xml如下:

<dependency> 
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-core-asl</artifactId> 
    <version>1.7.5</version> 
    <scope>compile</scope> 
</dependency> 
<dependency> 
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId> 
    <version>1.7.5</version> 
    <scope>compile</scope> 
</dependency> 
+0

我有这些作为Maven项目依赖.. – Sri 2011-04-12 07:21:07

1

这可能不是主要的问题,而是你的UserContext如果bean只有私有字段,bean将不能正常工作。有多种方法可以解决这个问题。从公开领域,到每个添加@JsonProperty,或者只是改变杰克逊用于检测属性字段的最小可见性(@JsonAutoDetect注释)。

但用空的JSON,这不应该给问题;如果有问题,你应该看到不同类型的错误/异常(我认为)。