3

我正在尝试对地址进行地理编码并在 java 中获取 lat/lng 坐标。我能够对地址进行地理编码并将其返回到 json 对象中,但我无法弄清楚如何使用 json-simple 来解析下面的 json 以获取 lat/lng。任何帮助表示赞赏。

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Minneapolis",
               "short_name" : "Minneapolis",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Hennepin County",
               "short_name" : "Hennepin County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Minnesota",
               "short_name" : "MN",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Minneapolis, MN, USA",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 45.05125,
                  "lng" : -93.193794
               },
               "southwest" : {
                  "lat" : 44.890144,
                  "lng" : -93.32916299999999
               }
            },
            "location" : {
               "lat" : 44.983334,
               "lng" : -93.26666999999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 45.05125,
                  "lng" : -93.193794
               },
               "southwest" : {
                  "lat" : 44.890144,
                  "lng" : -93.32916299999999
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

我尝试了很多不同的东西,但这是我最近的失败:

JSONObject json = (JSONObject)parser.parse(addressAsString);
JSONObject results = (JSONObject) json.get("results");    <-- LINE 186
JSONArray geometry = (JSONArray) results.get("geometry");

for(int i = 0; i < geometry.size(); i++) {
    JSONObject p = (JSONObject) geometry.get(i);
    System.out.println(p);
}

它产生这个堆栈跟踪:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
    at com.AddressGeocoder.geocode(AddressGeocoder.java:186)
    at com.AddressGeocoder.<init>(AddressGeocoder.java:48)
    at com.Geocoder.main(Geocoder.java:7)
4

4 回答 4

5

"results" 是一个 JSONArray,其中填充了(在这个例子中只有一个)JSONObjects。这些 JSONObjects 包含您预期的 JSONArray“几何”。以下是您修改的代码,因此它循环遍历结果并打印几何数据:

JSONObject json = (JSONObject)parser.parse(addressAsString);
JSONArray results = (JSONArray) json.get("results");
for (int i = 0; i < results.size(); i++) {
    // obtaining the i-th result
    JSONObject result = (JSONObject) results.get(i);
    JSONObject geometry = (JSONObject) result.get("geometry");
    JSONObject location = (JSONObject) geometry.get("location");
    System.out.println(location.get("lat"));
    System.out.println(location.get("lng"));
}
于 2013-08-29T21:44:02.353 回答
3

那是因为“结果”是一个 JSONArray。尝试:

JSONArray results = (JSONArray ) json.getJSONArray("results");
于 2013-08-29T21:30:21.430 回答
1

因此,让我为您分解它,以便您可以理解 JSON 中的 {} 表示对象 [] 表示数组。简单的?是的。

视觉崩溃

results 
   index 0 ->
            addressed_components(array)-->
                                       long_name(single entity)
                                       short_name(single entity)
                                       types(array)

            formatted_address(single entity)
            geometry(huge ass object with nested objects)
            types(array)
  • 基本上,在您现在拥有的代码中,结果 0 索引将包含“address_components”、“formatted_address”、“geometry”、“types”。(注意这都是一个对象)

  • “Address_components”是一个数组。

  • 其中包含多个“Address_components”。

  • “几何”只是一个非常非常大的对象,其中有许多不同的属性。

  • 最后类型是一个数组。


从数组中检索项目的伪代码,哟!

LOOP THROUGH JSON ARRAY
     ASSIGN OBJECT VALUES // getting different objects that are indexed in the array.

(如果您想查看代码以了解这一切是如何完成的,请告诉我)

人。

于 2013-08-29T21:51:10.470 回答
1

我使用net.sf.json库,但您可以使用逻辑

这是代码

import java.util.Iterator;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

public class Test {

    static String str = "{  \"results\" : [ {    \"address_components\" : [   {      \"long_name\" : \"Minneapolis\",      \"short_name\" : \"Minneapolis\",      \"types\" : [ \"locality\", \"political\" ]   },   {      \"long_name\" : \"Hennepin County\",      \"short_name\" : \"Hennepin County\",      \"types\" : [ \"administrative_area_level_2\", \"political\" ]   },   {      \"long_name\" : \"Minnesota\",      \"short_name\" : \"MN\",      \"types\" : [ \"administrative_area_level_1\", \"political\" ]   },   {      \"long_name\" : \"United States\",      \"short_name\" : \"US\",      \"types\" : [ \"country\", \"political\" ]   }    ],    \"formatted_address\" : \"Minneapolis, MN, USA\",    \"geometry\" : {   \"bounds\" : {      \"northeast\" : {     \"lat\" : 45.05125,     \"lng\" : -93.193794      },      \"southwest\" : {     \"lat\" : 44.890144,     \"lng\" : -93.32916299999999      }   },   \"location\" : {      \"lat\" : 44.983334,      \"lng\" : -93.26666999999999   },   \"location_type\" : \"APPROXIMATE\",   \"viewport\" : {      \"northeast\" : {     \"lat\" : 45.05125,     \"lng\" : -93.193794      },      \"southwest\" : {     \"lat\" : 44.890144,     \"lng\" : -93.32916299999999      }   }    },    \"types\" : [ \"locality\", \"political\" ] }  ],  \"status\" : \"OK\"}";

    public static void main(String[] args) {
        parseAndCheckJsonObj(str, "");
    }

    static void parseAndCheckJsonObj(Object str, Object key) {
        /*
         * Check whether str is Valid JSON
         *  String i.e. started by { [ or not
         */
        if (JSONUtils.mayBeJSON(str.toString())) {
            try {

                if (JSONUtils.isArray(str)) {
                    /*if block Check for str as a Json Array*/
                    JSONArray rootArr = JSONArray.fromObject(str);
                    for (int i = 0; i < rootArr.size(); i++) {
                        parseAndCheckJsonObj(rootArr.get(i), key);
                    }
                } else {
                    /*else block Check for str as a Json Object*/
                    JSONObject rootObj = JSONObject.fromObject(str);

                    Iterator keyIter = rootObj.keys();
                    while (keyIter.hasNext()) {
                        Object objKey = keyIter.next();
                        parseAndCheckJsonObj(rootObj.get(objKey), objKey);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            if (key.equals("lat"))
                System.out.println("Latitude is : " + str);
            else if (key.equals("lng"))
                System.out.println("Longitude is : " + str);
            else
                System.out.println(key + " : " + str);
        }
    }
}

我的输出是:

long_name : Minneapolis
short_name : Minneapolis
types : locality
types : political
long_name : Hennepin County
short_name : Hennepin County
types : administrative_area_level_2
types : political
long_name : Minnesota
short_name : MN
types : administrative_area_level_1
types : political
long_name : United States
short_name : US
types : country
types : political
formatted_address : Minneapolis, MN, USA
Latitude is : 45.05125
Longitude is : -93.193794
Latitude is : 44.890144
Longitude is : -93.329163
Latitude is : 44.983334
Longitude is : -93.26666999999999
location_type : APPROXIMATE
Latitude is : 45.05125
Longitude is : -93.193794
Latitude is : 44.890144
Longitude is : -93.329163
types : locality
types : political
status : OK
于 2013-08-30T08:06:04.317 回答