我有一个需要解析的json文件,但标准的json解析器不起作用,我不知道为什么。也许我做错了什么,有人可以帮我解决这个问题吗?
这是解析器类:
public class GeoJSONDeserializer {
public static Route routeFromGeoJsonDictionary(JSONObject json)
{
Route route = new Route();
try {
JSONArray features = json.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject geometry = features.getJSONObject(i).getJSONObject("geometry");
if (geometry.getString("type").equals("LineString"))
{
route.paths.add(routePathFromLineStringFeature(features.getJSONObject(i)));
} else if (geometry.getString("type").equals("Point"))
{
route.pois.add(poiFromPointFeature(features.getJSONObject(i)));
} else if (geometry.getString("type").equals("Polygon"))
{
route.paths.add(routeAnnotationFromPolygonFeature(features.getJSONObject(i)));
}
}
} catch (Exception e)
{}
return route;
}
public static Path routePathFromLineStringFeature(JSONObject json)
{
Path path = new Path();
try {
JSONObject geometry = json.getJSONObject("geometry");
JSONArray lineStringCoordinates = geometry.getJSONArray("coordinates");
for (int i = 0; i < lineStringCoordinates.length(); i++) {
String coordinatePair = lineStringCoordinates.getString(i);
String[] coords =
coordinatePair.substring(1, coordinatePair.length() - 2).split(",");
double lat = Double.parseDouble(coords[0]);
double lon = Double.parseDouble(coords[1]);
LatLng point = new LatLng(lon, lat);
path.coordinates.add(point);
}
} catch (Exception e)
{}
return path;
}
public static Path routeAnnotationFromPolygonFeature(JSONObject json)
{
Path path = new Path();
try {
JSONObject geometry = json.getJSONObject("geometry");
JSONArray lineStringCoordinates = json.getJSONArray("coordinates");
for (int i = 0; i < lineStringCoordinates.length(); i++) {
String coordinatePair;
if (i >= lineStringCoordinates.length())
{
coordinatePair = lineStringCoordinates.getString(0);
} else {
coordinatePair = lineStringCoordinates.getString(i);
}
String[] coords =
coordinatePair.substring(1, coordinatePair.length() - 2).split(",");
double lat = Double.parseDouble(coords[0]);
double lon = Double.parseDouble(coords[1]);
LatLng point = new LatLng(lon, lat);
path.coordinates.add(point);
}
} catch (Exception e)
{}
return path;
}
public static POI poiFromPointFeature(JSONObject json)
{
POI poi = new POI();
try {
JSONObject geometry = json.getJSONObject("geometry");
Log.e("no parsed", geometry.toString());
JSONObject properties = json.getJSONObject("properties");
poi.title = properties.getString("name");
poi.name = properties.getString("title");
poi.subtitle = properties.getString("desc");
try{
JSONArray coordinates = geometry.getJSONArray("coordinates");
poi.coordinates = new LatLng(coordinates.getDouble(1), coordinates.getDouble(0));
Log.e("parsed", coordinates.toString());
}catch (Exception e){
Log.e("error", e.getMessage());
}
} catch (Exception e)
{}
return poi;
}}
然后这是我的日志输出:
您可以看到一些未解析的字符串已被解析,而另一些则未解析。这不是一个随机问题,因为它总是发生在同一个问题上。
以下是json文件的链接:
我希望有人可以帮我解决这个问题。
答案 0 :(得分:1)
我必须使用optString
而不是getString
,因此解析器不会在尝试中崩溃