我正在使用RestTemplate并且在反序列化对象时遇到问题。这就是我在做的事情。 JSON响应看起来像,
{
"response": {
"Time": "Wed 2013.01.23 at 03:35:25 PM UTC",
"Total_Input_Records": 5,
},-
"message": "Succeeded",
"code": "200"
}
将此Json有效负载转换为POJO
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
}
以下是我收到异常的请求处理,
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: org.apache.http.conn.EofSensorInputStream@340ae1cf; line: 1, column: 22 (through reference chain: com.temp.pointtests.MyClass["response"]->com.temp.pointtests.Response["Time"]);]
+++++更新已解决+++++++非洲
我看到Spring添加了使用Jackson 2的MappingJackson2HttpMessageConverter。因为我上面的代码中的MappingJacksonHttpMessageConverter使用的是Jackson Pre2.0版本,但它不起作用。但它适用于Jackson 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 :(得分:0)
使用org.codehaus.jackson.map.JsonDeserializer的@JsonSerialize(using = JsonDateSerializer.class)或@JsonDeserialize(using = JsonDateDeSerializer.class)注释;它将解决问题或用户ObjectMapper(org.codehaus.jackson.map.ObjectMapper)转换为Json String。
objectMapper.writeValueAsString(对象); //这将给出json字符串