Uso la API REST de MapBox en el backend para crear una ruta. Aquí hay un código simplificado:
public class MapBoxRequest { // using string pattern just for convenience private static final String PATTERN = "https://api.mapbox.com/directions/v5/mapbox/walking/%s,%s;%s,%s?alternatives=true&geometries=geojson&steps=true&access_token=%s"; public static void main(String[] args) throws IOException, URISyntaxException { HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(); String accessToken = "access_toekn"; // set right location values String string = String.format(PATTERN, longitude1, latitude1, longitude2, latitude2, accessToken); URI uri = new URI(string); HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri.toString())); String rawResponse = request.execute().parseAsString(); // HERE I AM GETTING EXCEPTION, THIS CODE IS SUPPOSED TO BE CALLED IN ANDROID APP DirectionsResponse.fromJson(rawResponse); } }con estas dependencias expertas:
<dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client</artifactId> <version>1.38.0</version> </dependency> <dependency> <groupId>com.mapbox.mapboxsdk</groupId> <artifactId>mapbox-sdk-services</artifactId> <version>5.6.0</version> </dependency> Pero cuando trato de analizar la clase DirectionsResponse de la cadena, obtengo la siguiente excepción:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 546 path $.routes[0].legs[0].steps[0].geometry at com.google.gson.Gson.fromJson(Gson.java:939) at com.google.gson.Gson.fromJson(Gson.java:892) at com.google.gson.Gson.fromJson(Gson.java:841) at com.google.gson.Gson.fromJson(Gson.java:813) at com.mapbox.api.directions.v5.models.DirectionsResponse.fromJson(DirectionsResponse.java:133) at dating.walking.service.walking.setup.MapBoxRequest.main(MapBoxRequest.java:34) Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 546 path $.routes[0].legs[0].steps[0].geometry at com.google.gson.stream.JsonReader.nextString(JsonReader.java:825) El código anterior es por ejemplo. En la práctica, se supone que los clientes de Android/iOS deben descargar ese JSON, analizarlo y usarlo en la navegación usando MapBox Navigation SDK . La cuestión es que en la aplicación de Android obtengo la misma excepción que la anterior.
Mi pregunta es: ¿cómo puedo crear una ruta en un lado de back-end, enviarla al cliente como json y analizar JSON y comenzar a navegar?
Usar MapBox Java SDK en lugar de MapBox REST API y configurar la biblioteca Gson me ayudó a serializar y deserializar la clase ReponseRoute .
Aquí hay un código simplificado:
public class MapBoxSdkSample { public static void main(String[] args) { String accessToken = "*****"; Point originPoint = Point.fromLngLat(**, **); Point destinationPoint = Point.fromLngLat(**, **); MapboxDirections client = MapboxDirections.builder() .origin(originPoint) .destination(destinationPoint) .overview(DirectionsCriteria.OVERVIEW_FULL) .profile(DirectionsCriteria.PROFILE_WALKING) .accessToken(accessToken) .build(); client.enqueueCall( new Callback<>() { @Override public void onResponse( Call<DirectionsResponse> call, Response<DirectionsResponse> response) { // boilerplate code if (response.body() == null) { System.out.println( "No routes found, make sure you set the right user and access token."); return; } else if (response.body().routes().size() < 1) { System.out.println("No routes found"); return; } DirectionsRoute directionsRoute = response.body().routes().get(0); Gson gson = new GsonBuilder() .registerTypeAdapterFactory(DirectionsAdapterFactory.create()) .create(); String s1 = gson.toJson(directionsRoute); // I wasn't getting exceptions here and the object was populated with data DirectionsRoute parsedFromJsonRoute = gson.fromJson(s1, DirectionsRoute.class); } @Override public void onFailure(Call<DirectionsResponse> call, Throwable throwable) { System.out.println("Error: " + throwable.getMessage()); } }); } }