Дезериализация вложенных объектов с использованием ResttemplateJAVA

Программисты JAVA общаются здесь
Anonymous
Дезериализация вложенных объектов с использованием Resttemplate

Сообщение Anonymous »

Я использую Resttemplate и имею проблемы, опустошенные детериализации объекта. Вот что я делаю. Ответ JSON выглядит как, < /p>
{
"response": {
"Time": "Wed 2013.01.23 at 03:35:25 PM UTC",
"Total_Input_Records": 5,
},-
"message": "Succeeded",
"code": "200"
}
< /code>
Преобразовал эту полезную нагрузку JSON в POJO, используя Jsonschema2pojo < /p>
public class MyClass {
@JsonProperty("response")
private Response response;
@JsonProperty("message")
private Object message;
@JsonProperty("code")
private Object code;
private Map additionalProperties = new HashMap();
//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 additionalProperties = new HashMap();
//bunch of getters and setters here
}
< /code>
Вот обработка запроса, где я получаю исключение, < /p>
String url = "http://example.com/someparams";
RestTemplate template = new RestTemplate(
new HttpComponentsClientHttpRequestFactory());
FormHttpMessageConverter converter = new FormHttpMessageConverter();
List mediaTypes = new ArrayList();
mediaTypes.add(new MediaType("application", "x-www-form-urlencoded"));
converter.setSupportedMediaTypes(mediaTypes);
template.getMessageConverters().add(converter);
MyClass upload = template.postForObject(url, null, MyClass.class);
< /code>
Вот разочарующая часть, исключение (намеренно триммированная, а не полная). Что -нибудь мне не хватает? < /P>
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 добавил MappingJackson2httpmessageConverter, который использует Jackson 2. Потому что картирование JacksonhtpmessageConverter в моем коде выше использует версии Jackson Pre2.0, и это не работает. Это работает для Jackson 2.0, однако. С помощью MappingJackson2httpmessageConverter теперь я теперь могу добавить его в свой Resttemplate, и все работает нормально :-). Вот код для людей, у которых такая же проблема, < /p>
String url = "http://example.com/someparams";
RestTemplate template = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity request = new HttpEntity(headers);
List>();
MappingJackson2HttpMessageConverter map = new MappingJackson2HttpMessageConverter();
messageConverters.add(map);
messageConverters.add(new FormHttpMessageConverter());
template.setMessageConverters(messageConverters);
MyClass msg = template.postForObject(url, request, MyClass.class);


Подробнее здесь: https://stackoverflow.com/questions/144 ... sttemplate

Вернуться в «JAVA»