I use MapBox REST API on backend side to create a route. Here is a simplified code:
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);
}
}
with these maven dependencies:
<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>
But when I try to parse DirectionsResponse class from string I am getting the following exception:
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)
The code above is for example. In practice Android/iOS clients are supposed to download that JSON, parse it and use it in navigation using MapBox Navigation SDK. The thing is in Android application I am getting the same exception as the one above.
My question is - how can I create a route on a backend side, send it to client as json and parse JSON and start navigation?
Using
MapBox Java SDKinstead ofMapBox REST APIand configuringGsonlibrary helped me serialize and deserializeReponseRouteclass.Here is a simplified code: