简体   繁体   中英

How to extract a json object from a json array by name in java?

I'm recieving JSON from the Google Directions API and the request is like the one shown here (under Directions Responses -> Json Output) link

I don't know how to extract a particular entry from within a json array. Basically what I need is the JsonArray equivalent of JSONObject method get(String key) where you can get the entry mapped to a specific key. However, the JSONArray has no such method, and seems to only support the retrieval of info through a specific index. This is all well and good, but the google directions reponses' contents can vary - so I need a way to either find a specific key-value pairing, or loop through the entire array and have a way to check the value of the key. I could even find a way to determine the key that a JSONObject was mapped to. Any suggestions? Ex: How would you extract the distance JSONObject out of the JSONArray legs?

Edit: This is where I am stuck: Refering the the JSON example output here ... I am trying to get the value of the "overview_polyline" entry within the "routes" json array. Since I cannot access the "overview_polyline" entry simply by referring to its name, I must loop through the array until I get to that entry. But how would I know when I got to that entry? Yes, perhaps I could check if the JSONObject representation of the entry had a "points" key, but that isn't necessarily exclusive to the "overview_polyline" entry. Also, I cannot simply get the (array.length() - n) entry because the number of entries returned in the array may vary. In short, it seems to me that I need a way to check the name ("overview_polyline") of each JSONObject to reliably be able to extract that information.

            JSONArray routesArray = resultObj.getJSONArray("routes");

            for(int i = 0; i < routesArray.length(); i++)
            {
                JSONObject obj = routesArray.optJSONObject(i);
                if(obj != null) 
                {
                    //How do I determine if this object is the "overview_polyline" 
                    //object?
                }
            }

The route is a JSONArray of JSONObject , so you have to do it this way:

JSONArray routesArray = resultObj.getJSONArray("routes");
for(int i = 0; i < routesArray.length(); i++) {
    JSONObject obj = routesArray.optJSONObject(i);
    if(obj != null) {
        JSONObject polyline = obj.optJSONObject("overview_polyline");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM