简体   繁体   中英

How to access JSON value

Unsure how to access the "points" value in this JSON. I am a beginner and have read tutorials but I still do not understand how to get to this value as it isn't in it's own array like [] and instead uses {}.

EDIT

I managed to solve this, this line in my for loop needed to be cast to String:

polyline = (String) objPoints.get("points");

EDIT:

I have tried another approach, however I cannot get the data I want. My code won't produce an output, my System.out.println doesn't show in the console.

public void getDirections() {
    try {

        String polyline = "";

        URL url = new URL("https://maps.googleapis.com/maps/api/directions/json?origin=Bournemouth+University&destination=" + houseNumber + "+" + address + "+" + city + "&key=AIzaSyBn2qYJcHoNCgNQZv1mcycnUo06sJDZPBs");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        int responseCode = conn.getResponseCode();

        if (responseCode != 200) {
            throw new RuntimeException("HttpResponseCode: " + responseCode);
        } else {


            Scanner scan = new Scanner(url.openStream());
            StringBuilder jsonIn = new StringBuilder();
            while (scan.hasNextLine()) {
                jsonIn.append(scan.nextLine());

            }
            scan.close();

            System.out.println(jsonIn.toString());

            JSONParser parser = new JSONParser();
            JSONObject objRoot = (JSONObject) parser.parse(jsonIn.toString());
            JSONArray routesArray = (JSONArray) objRoot.get("routes");


            for (int i = 0; i < routesArray.size(); i ++) {
                JSONObject objOverviewPolyline = (JSONObject) routesArray.get(i);
                JSONObject objPoints = (JSONObject) objOverviewPolyline.get("overview_polyline");
                polyline = objPoints.get("points").toString();
            }

            System.out.println("POLYLINE " + polyline);

        }

    }catch (Exception e) {
        e.printStackTrace();
    }

JSON ("points" value is right at the bottom):

https://maps.googleapis.com/maps/api/directions/json?origin=Bournemouth+University&destination=London+England&key=AIzaSyBn2qYJcHoNCgNQZv1mcycnUo06sJDZPBs

Here is my code so far, it generates this error:

Unexpected token RIGHT BRACE(}) at position 0.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at CustomerMap.getDirections(CustomerMap.java:73)
at CustomerMap.<init>(CustomerMap.java:39)

CustomerMap class code:

JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject)parser.parse(result);
JSONArray jsonArray = (JSONArray)jObj.get("routes");

    for (int i = 0; i < jsonArray.size(); i ++) {
            JSONObject jObjPolyline = (JSONObject)jsonArray.get(i);
            JSONObject jObjPoints = (JSONObject)jObjPolyline.get("overview_polyline");
            JSONArray jsonPolylineArray = (JSONArray)jObjPolyline.get("points");

                for (int j = 0; j < jsonPolylineArray.size(); j ++) {
                    polyline = jsonPolylineArray.get(j).toString();
                }
    }

I'm sure this is a very simple question and I know someone will mark this as a duplicate question but I just wanted some help with this thanks.

Well, regarding the retrieval of points : what helps me most is first to assemble the correct JSON path in my mind. There are plenty of tools to do so, eg http://jsonpath.com/

So you can find that your points objects can be found here:

routes[*].legs[*].steps[*].polyline.points

If this is not enough information to augment your implementation here is a working example:

import static org.assertj.core.api.Assertions.assertThat;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParserTest {
    @Test
    public void points() throws Exception {
        String jsonString = FileUtils.readFileToString(new File(JsonParserTest.class.getResource("/points.json").getFile()), "UTF-8");
        List<String> points = new ArrayList<>();

        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(jsonString);

        // routes[*].legs[*].steps[*].polyline.points
        Iterator<JsonNode> routes = actualObj.get("routes").elements();
        while (routes.hasNext()) {
            Iterator<JsonNode> legs = routes.next().get("legs").elements();
            while (legs.hasNext()) {
                Iterator<JsonNode> steps = legs.next().get("steps").elements();
                while (steps.hasNext()) {
                    points.add(steps.next().get("polyline").get("points").asText());
                }
            }
        }
        System.out.println(points);
        assertThat(points.size()).isGreaterThan(0);
    }
}

A rather straight-forward approach which shows especially the nested structure of the JSON. May be you should additionally consider implementing a certain POJO for the complete structure… then parsing would be as easy as:

import com.fasterxml.jackson.databind.ObjectMapper;

new ObjectMapper().readValue(jsonString, PojoRepresentingTheJson.class);

And the points at the bottom of the document can be reached directly with the routes object from above:

routes.next().get("overview_polyline").get("points").asText()

1- build the classes of this object

2- go and check this it may helps you Gson

It is easier if you write out the JSON structure first.

If you are trying to access the points value in overview_polyline ,

root.routes[i].overview_polyline.points

you can do it using the following code:

for (int i = 0; i < jsonArray.size(); i++) {
    JSONObject route = jsonArray.get(i);
    JSONObject jObjPolyline = route.get("overview_polyline");
    JSONObject jObjPoint = jObjPolyline.get("points");
}

If you are trying to access the points value in steps ,

root.routes[i].legs[j].steps[k].polyline.points

you can do it like this:

for (int i = 0; i < jsonArray.size(); i++) {
    JSONObject route = (JSONObject) jsonArray.get(i);
    for (JSONObject leg: route.get("legs")) {
        for (JSONObject step: leg.get("steps)) {
            JSONObject points = step.get("polyline").get("points");
}

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