2013-06-29 83 views
2

Bleow是必須通過使用Spring Rest模板轉換爲對象的json。Spring RestTemplate的JSON反序列化問題

{"userResponse": { 
    "build": 1, 
    "code": 400, 
    "status": "Failed", 
    "validationErrors": [ 
      { 
     "fieldName": "userId", 
     "message": "User Id is NOT in valid format" 
     }, 
      { 
     "fieldName": "password", 
     "message": "Password cannot be less than 8 characters" 
     } 
    ] 
}} 

當validationErrors的元素列表是響應的一部分時,問題出現在這裏。

下面是彈簧休息模板配置。

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> 
    <property name="messageConverters"> 
     <list> 
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >   
       <property name="supportedMediaTypes" value="application/json" /> 
      </bean>    
     </list> 
    </property> 
</bean> 

下面是調用postForObject的代碼。

restTemplate.postForObject("ServiceUrl", "userinput", Registration.class);

下面是錯誤引發,而調用服務。

org.springframework.web.client.HttpClientErrorException: 400 Bad Request 
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:90) 
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:494) 
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:451) 
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:409) 

請提供一些意見以解決問題。

+0

你的'Registration'類是什麼樣的? –

回答

0

您的「userinput」需要是JSON格式的字符串,並且不是,因此您嘗試聯繫的服務可能會回覆「不良請求」,因爲您沒有發送有效的JSON。

API documentation告訴您如何爲該方法設置參數格式。您應該確保要發佈的格式正確的JSON(我推薦使用Java對象,序列化,使用傑克遜是這樣的:

+0

我可以發送請求使用postForObject方法服務,「userinput」是請求對象,「ServiceUrl是實際的URL」,但問題是當響應包含指定的對象列表時在示例中,JSON不是反序列化到Object中。注意:如果響應不包含對象列表,則反序列化。 – user2533804

0

如上所述你"userinput"應該是有效的JSON(例如{"userinput" : {"dataKey" : "dataValue"}}) 。也不清楚"ServiceUrl"是否是你提供的代碼片段中的實際URL的佔位符,請確保URL也有效。