2013-01-23 34 views
6

我正在使用RestTemplate并且存在反序列化对象的问题。这是我正在做的。 JSON响应样子,使用RestTemplate反序列化嵌套对象

{ 
"response": { 
"Time": "Wed 2013.01.23 at 03:35:25 PM UTC", 
"Total_Input_Records": 5, 
},- 
"message": "Succeeded", 
"code": "200" 
} 

转换此JSON的有效载荷送入使用jsonschema2pojo

public class MyClass { 
    @JsonProperty("response") 
    private Response response; 
    @JsonProperty("message") 
    private Object message; 
    @JsonProperty("code") 
    private Object code; 
    private Map<String, Object> additionalProperties = new HashMap<String, Object>(); 
    //bunch of getters and setters here 
} 
public class Response { 
    @JsonProperty("Time") 
    private Date Time; 
    @JsonProperty("Total_Input_Records") 
    private Object Total_Input_Records; 
    private Map<String, Object> additionalProperties = new HashMap<String, Object>(); 
//bunch of getters and setters here 
} 

这里就是我得到异常请求处理一个POJO,

String url = "http://my.site.com/someparams"; 
RestTemplate template = new RestTemplate(
       new HttpComponentsClientHttpRequestFactory()); 
FormHttpMessageConverter converter = new FormHttpMessageConverter(); 
List<MediaType> mediaTypes = new ArrayList<MediaType>(); 
mediaTypes.add(new MediaType("application", "x-www-form-urlencoded")); 
converter.setSupportedMediaTypes(mediaTypes); 
template.getMessageConverters().add(converter); 
MyClass upload = template.postForObject(url, null, MyClass.class); 

这里令人沮丧的部分,例外(故意修剪,而不是完整)。我错过了什么?

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized field "Time" (Class com.temp.pointtests.Response), not marked as ignorable 
at [Source: [email protected]; line: 1, column: 22 (through reference chain: com.temp.pointtests.MyClass["response"]->com.temp.pointtests.Response["Time"]);] 

+++++更新解决++++++

我看到了春天加入MappingJackson2HttpMessageConverter它使用杰克逊2.由于MappingJacksonHttpMessageConverter在我上面的代码使用了杰克逊Pre2.0版本和它不工作。但它适用于杰克逊2.0。随着MappingJackson2HttpMessageConverter现在可用,我现在可以将它添加到我的RestTemplate并且一切工作正常:-)。这里是谁具有相同的问题,人的代码,

String url = "http://mysite.com/someparams"; 
RestTemplate template = new RestTemplate(); 
HttpHeaders headers = new HttpHeaders(); 
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); 
HttpEntity request = new HttpEntity(headers); 
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); 
MappingJackson2HttpMessageConverter map = new MappingJackson2HttpMessageConverter(); 
messageConverters.add(map); 
messageConverters.add(new FormHttpMessageConverter()); 
template.setMessageConverters(messageConverters); 
MyClass msg = template.postForObject(url, request, MyClass.class); 
+0

你应该用问题的“更新编辑”回答你自己的问题。 – hectorg87

回答

0

使用@JsonSerialize(使用= JsonDateSerializer.class)或@JsonDeserialize(使用= JsonDateDeSerializer.class)org.codehaus.jackson.map的注解。 JsonDeserializer;它会解决问题或用户ObjectMapper(org.codehaus.jackson.map.ObjectMapper)转换为Json String。

objectMapper.writeValueAsString(Object); //这将给json字符串

相关问题