El error te dice que estás tratando de convertir una String
en una List<BusStop>
:
Cannot convert value of type 'java.lang.String' to required type 'es.ticnor.trayecbus.model.BusStop'
Si estás pasando una String
en formato JSON
al @Controller
, utiliza un parser como Jackson para procesarla y convertirla al objeto o lista de objetos que deseas.
Suponiendo que tienes una clase llamada BusStop:
public class BusStop {
private double lat;
private double lng;
private String description;
public BusStop() {
}
public BusStop(double lat, double lng, String description) {
this.lat = lat;
this.lng = lng;
this.description = description;
}
//getters and setters ....
}
En esta clase hago el procesado:
package com.so.victor;
import java.io.IOException;
import java.util.List;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class TestSO {
private static String json = "[{\"lat\":43.4721537946863,\"lng\":-3.8495182526509097,\"description\":\"2\"},{\"lat\":43.4721537946863,\"lng\":-3.8495182526509097,\"description\":\"2\"},{\"lat\":43.4721537946863,\"lng\":-3.8495182526509097,\"description\":\"2\"}]";
public static void main(String[] args) {
List<BusStop> mylist = convertBusStop();
mylist.forEach(c -> {
System.out.println(c.getLat());
});
}
private static List<BusStop> convertBusStop() {
ObjectMapper mapper = new ObjectMapper();
List<BusStop> myObjects = null;
try {
myObjects = mapper.readValue(json,
mapper.getTypeFactory().constructCollectionType(List.class, BusStop.class));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return myObjects;
}
}
He utilizado esta versión de jackson:
<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>