我打电话给这个网址
http://maps.googleapis.com/maps/api/geocode/json?latlng=18.550455,73.920148&sensor=true
并得到回复(我从中间删除了很多回复,因为它与问题无关。
{
"results" : [
{
"address_components" : [
{
"long_name" : "Towards Wadgao Sheri",
"short_name" : "Towards Wadgao Sheri",
"types" : [ "route" ]
},
{
"long_name" : "411014",
"short_name" : "411014",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Towards Wadgao Sheri, Sainikwadi, Wadgaon Sheri, Pune, Maharashtra 411014, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 18.55131630,
"lng" : 73.91882219999999
},
"southwest" : {
"lat" : 18.55024130,
"lng" : 73.91866569999999
}
},
"location" : {
"lat" : 18.55077720,
"lng" : 73.91878240
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 18.55212778029150,
"lng" : 73.92009293029150
},
"southwest" : {
"lat" : 18.54942981970850,
"lng" : 73.91739496970848
}
}
},
"types" : [ "route" ]
},
{
"address_components" : [
{
"long_name" : "Sainikwadi",
"short_name" : "Sainikwadi",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "411014",
"short_name" : "411014",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Sainikwadi, Wadgaon Sheri, Pune, Maharashtra 411014, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 18.5551140,
"lng" : 73.92143690
},
"southwest" : {
"lat" : 18.5465270,
"lng" : 73.91406809999999
}
},
"location" : {
"lat" : 18.55092520,
"lng" : 73.91687659999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 18.5551140,
"lng" : 73.92143690
},
"southwest" : {
"lat" : 18.5465270,
"lng" : 73.91406809999999
}
}
},
"types" : [ "neighborhood", "political" ]
},
{
"address_components" : [
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 35.50447520,
"lng" : 97.3955550
},
"southwest" : {
"lat" : 6.747138899999999,
"lng" : 68.16238590
}
},
"location" : {
"lat" : 20.5936840,
"lng" : 78.962880
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 35.50447520,
"lng" : 97.3955550
},
"southwest" : {
"lat" : 6.747138899999999,
"lng" : 68.16279560
}
}
},
"types" : [ "country", "political" ]
}
],
"status" : "OK"
}
代码
JsonObject response = new JsonObject().getAsJsonObject(jsonResults.toString());
>>>NPE JsonArray results = response.getAsJsonArray("results");
来自 json 的响应在 jsonResults 中。我在第二行得到一个 NPE
我想响应是空的,我想知道为什么,这里做错了什么?刚刚从响应 json 中创建了一个 json 对象。我知道我在这里错过了一些非常愚蠢的东西。
编辑 :
Exception in thread "Thread-0" java.lang.NullPointerException
at com.mcruiseon.ivr.God.getGeoAddress(God.java:141)
编辑 2:
我已经稍微编辑了 json 响应。请注意。我也在尝试提取formatted_address
编辑 3:
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;