No se pudo leer JSON: No se puede deserializar instancia de hola.País [] token de OBJETO fuera de INICIO
Tengo url rest que me da todos los países - http://api.geonames.org/countryInfoJSON?username=volodiaL .
Utilizo RestTemplate de spring 3 para analizar json devuelto en objetos java:
RestTemplate restTemplate = new RestTemplate();
Country[] countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",Country[].class);
Cuando corro este código obtengo una excepción:
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of hello.Country[] out of START_OBJECT token
at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@1846149; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:691)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:685)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.handleNonArray(ObjectArrayDeserializer.java:222)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:133)
at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:18)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2993)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:225)
... 7 more
Finalmente mi clase de País:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Country {
private String countryName;
private long geonameId;
public String getCountryName() {
return countryName;
}
public long getGeonameId() {
return geonameId;
}
@Override
public String toString() {
return countryName;
}
}
El problema es que json devuelto contiene el elemento raíz "geonames" que contiene una matriz de elementos country como así:
{
"geonames": [
{
"continent": "EU",
"capital": "Andorra la Vella",
"languages": "ca",
"geonameId": 3041565,
"south": 42.42849259876837,
"isoAlpha3": "AND",
"north": 42.65604389629997,
"fipsCode": "AN",
"population": "84000",
"east": 1.7865427778319827,
"isoNumeric": "020",
"areaInSqKm": "468.0",
"countryCode": "AD",
"west": 1.4071867141112762,
"countryName": "Andorra",
"continentName": "Europe",
"currencyCode": "EUR"
}
]
}
Cómo decirle a RestTemplate
que se convierta cada elemento de matriz en Country
objeto?
5 answers
Necesitas hacer lo siguiente:
public class CountryInfoResponse {
@JsonProperty("geonames")
private List<Country> countries;
//getter - setter
}
RestTemplate restTemplate = new RestTemplate();
List<Country> countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",CountryInfoResponse.class).getCountries();
Sería genial si pudieras usar algún tipo de anotación para permitirte saltar niveles, pero aún no es posible (ver this and this)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-21 12:07:27
Otra solución:
public class CountryInfoResponse {
private List<Object> geonames;
}
El uso de un objeto genérico -List resolvió mi problema, ya que había otros tipos de datos como Booleano también.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-05 16:59:08
En mi caso, estaba obteniendo el valor de <input type="text">
con jQuery y lo hice así:
var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
"firstName": inputFirstName[0] , "email": inputEmail[0].value}
Y yo estaba constantemente recibiendo esta excepción
Com.fasterxml.jackson.databind.JsonMappingException: No se puede deserializar instancia de java.lang.String out of START_OBJECT token en [Fuente: java.io.PushbackInputStream@39cb6c98; line: 1, column: 54] (through reference chain: com.springboot.dominio.User ["FirstName"]).
Y me golpeé la cabeza durante una hora hasta que me di cuenta de que me olvidé de escribir .value
después de esto"firstName": inputFirstName[0]
.
Entonces, la solución correcta fue:
var newUserInfo = { "lastName": inputLastName[0].value, "userName": inputUsername[0].value,
"firstName": inputFirstName[0].value , "email": inputEmail[0].value}
Vine aquí porque tenía este problema y espero ahorrarle a alguien horas de miseria.
Saludos:)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-31 17:31:42
Si desea evitar usar un Class
y List<Object> genomes
extra, simplemente podría usar un Map
.
La estructura de datos se traduce en Map<String, List<Country>>
String resourceEndpoint = "http://api.geonames.org/countryInfoJSON?username=volodiaL";
Map<String, List<Country>> geonames = restTemplate.getForObject(resourceEndpoint, Map.class);
List<Country> countries = geonames.get("geonames");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-04 17:03:04
Para Spring-boot 1.3.3 el método exchange () para List está funcionando como en la respuesta correspondiente
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:10