2011-04-11 96 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,這不應該給問題;如果有問題,你應該看到不同類型的錯誤/異常(我認爲)。