我在后端使用mapboxrestapi来创建路由。下面是一个简化的代码:
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);
}
}
使用这些maven依赖项:
<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>
但当我试图分析 DirectionsResponse
从字符串初始化我得到以下异常:
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)
上面的代码就是一个例子。实际上,android/ios客户机应该下载json,解析它,并在导航中使用它 MapBox Navigation SDK
. 事情是在android应用程序中,我得到了和上面一样的异常。
我的问题是-如何在后端创建路由,将其作为json发送到客户端,解析json并启动导航?
1条答案
按热度按时间8i9zcol21#
使用
MapBox Java SDK
而不是MapBox REST API
和配置Gson
库帮助我序列化和反序列化ReponseRoute
班级。下面是一个简化的代码: