简体   繁体   中英

How to access JSON value?

Very new to JSON, this is probably very simple but I'm not sure how to access the "coordinates" in this JSON I know how to go from resourceSets to resources but get stuck at "point":

{
   "resourceSets":[
      {
         "estimatedTotal":1,
         "resources":[
            {
               "__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
               "bbox":[
                  51.3223903,
                  -0.2634519,
                  51.3246386,
                  -0.2598541
               ],
               "name":"name",
               "point":{
                  "type":"Point",
                  "coordinates":[
                     51.3235145,
                     -0.261653
                  ]
               }
            }
        ]
      }
   ]
}

My code so far:

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

                for (int i = 0; i < jsonArray.size(); i ++) {
                    JSONObject jObjResourceSets = (JSONObject)jsonArray.get(i);
                    JSONArray jsonArray2 = (JSONArray)jObjResourceSets.get("resources");
                    System.out.println("Coords" + jObjResourceSets.get("point"));


                }

Normally this code works for the given JSON object. However I'll put the tested formatted JSON value below the java code so you can test it as well.

Note that this code will get you all the coordinates of all the elements in your object.

public static void main(String[] args) throws Exception {

    String result = getJsonString();
    // Getting root object
    JSONParser parser = new JSONParser();
    JSONObject jObj = (JSONObject)parser.parse(result);
    // Getting resourceSets Array
    JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");

    for (int i = 0; i < jsonArray.size(); i++) {
        // Getting the i object of resourceSet
        JSONObject jObjResourceSets = (JSONObject) jsonArray.get(i);
        // Getting resources list of the current element
        JSONArray jsonArray2 = (JSONArray) jObjResourceSets.get("resources");
        for (int j = 0; j < jsonArray2.size(); j++) {
            // Getting the j resource of the resources array
            JSONObject resource = (JSONObject) jsonArray2.get(j);
            // Getting the point object of the current resource
            JSONObject point = (JSONObject) resource.get("point");
            // Getting the coordinates list of the point
            JSONArray coordinates = (JSONArray) point.get("coordinates");
            for (int k = 0; k < coordinates.size(); k++) {
                System.out.println("Coordinates[" + k + "]: " + coordinates.get(k));
            }
            // Printing an empty line between each object's coordinates
            System.out.println();
        }
    }
}

The tested JSON Object:

{
   "resourceSets":[
      {
         "estimatedTotal":1,
         "resources":[
            {
               "__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
               "bbox":[
                  51.3223903,
                  -0.2634519,
                  51.3246386,
                  -0.2598541
               ],
               "name":"name",
               "point":{
                  "type":"Point",
                  "coordinates":[
                     51.3235145,
                     -0.261653
                  ]
               }
            }
        ]
      }
   ]
}

If it worked please mark it as the answer.

Good luck ^^

B.

Lets analyse what you're doing (and need to be doing), step by step , in order to get the "coordinates".

First of all, JSON is a great language to transfer static data. It works like a dictionary, where you have a key and the respective value. The key should always be a String, but the value can be a String, an int/double or even an array of other JSON objects. That's what you have.

For instance, "estimatedTotal" is an element ( JSONObject ) from the "resourceSet" array ( JSONArray ).

JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");

What you're saying here is straight forward: from your overall JSONObject - jObj - you want to extract the array with key "resourceSets".

Now you have direct access to "resourceSets" array elements: "estimatedTotal", "resources", etc. So, by applying the same logic, in order to access "coordinates" we need to access the "resources" array. And by that I mean to create a JSONArray object like we did before.

JSONArray jsonResourcesArray = (JSONArray)jObjResourceSets.get("resources");

I hope it's clear what's the content of jsonResourcesArray here. It's the JSON array of "__type", "bbox", "name", "point", (...). The Coordinates howevere are inside "point" JSON object. How do we access it?

JSONObject jsonPointObject = (JSONObject) jsonResourcesArray.get("point");

And you know by know that "jsonPointObject" has as its values the following JSON objects: "type" and "coordinates". Coordinates is an array of values, so do we have to use JSONArray or JSONObject?

JSONArray jsonCoordinatesArray = (JSONArray) jsonPointObject.get("coordinates");

From which we mean: from the jsonPointObject we want to extract the array that has key "coordinates". Now your array is a JSONArray with values of jsonCoordinatesArray.get(0) and jsonCoordinatesArray.get(0) .

Now you have, not only the code to get those values, but the understanding of how JSON works and how Java interacts with it so you can solve any Json problem from now on.

You need the following piece of code to get the data.

JSONArray jsonArray2 = (JSONArray)jObjResourceSets.get("resources");
        /**
         * here we should note that the "resources" is only having one JSON object hence we can take it as below
         * from 0th index using ((JSONObject)jsonArray2.get(0)) these piece of code and the next part is to take the point JSONObject 
         * from the object.
         */
        JSONObject temp = (JSONObject)((JSONObject)jsonArray2.get(0)).get("point"); 
        System.out.println("Coords"+temp.get("coordinates")); //this will give you the coordinates array

        //now if you want to do further processing, traverse in the jsonArray like below
        JSONArray arr= (JSONArray)temp.get("coordinates");
        System.out.println("X coordinate:"+arr.get(0));
        System.out.println("Y coordinate:"+arr.get(1)); 

For more information and further details on JSONObject and JSONArray you can go through this link
parsing-jsonarray-and-jsonobject-in-java-using-json-simple-jar

json-simple-example-read-and-write-json

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