Retrieving values from nested JSON Object

后端 未结 6 1270
星月不相逢
星月不相逢 2020-12-02 19:37

I\'ve got JSON file, which I want to parse. The JSON file (\"myfile\") has format as follows:

{
    \"LanguageLevels\": {
        \"1\": \"Początkujący\",
           


        
相关标签:
6条回答
  • 2020-12-02 19:54

    Maybe you're not using the latest version of a JSON for Java Library.

    json-simple has not been updated for a long time, while JSON-Java was updated 2 month ago.

    JSON-Java can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java

    After switching the library, you can refer to my sample code down below:

    public static void main(String[] args) {
        String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
    
        JSONObject jsonObject = new JSONObject(JSON);
        JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
        Object level = getSth.get("2");
    
        System.out.println(level);
    }
    

    And as JSON-Java open-sourced, you can read the code and its document, they will guide you through.

    Hope that it helps.

    0 讨论(0)
  • 2020-12-02 19:56

    You will have to iterate step by step into nested JSON.

    for e.g a JSON received from Google geocoding api

    {
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "Bhopal",
                   "short_name" : "Bhopal",
                   "types" : [ "locality", "political" ]
                },
                {
                   "long_name" : "Bhopal",
                   "short_name" : "Bhopal",
                   "types" : [ "administrative_area_level_2", "political" ]
                },
                {
                   "long_name" : "Madhya Pradesh",
                   "short_name" : "MP",
                   "types" : [ "administrative_area_level_1", "political" ]
                },
                {
                   "long_name" : "India",
                   "short_name" : "IN",
                   "types" : [ "country", "political" ]
                }
             ],
             "formatted_address" : "Bhopal, Madhya Pradesh, India",
             "geometry" : {
                "bounds" : {
                   "northeast" : {
                      "lat" : 23.3326697,
                      "lng" : 77.5748062
                   },
                   "southwest" : {
                      "lat" : 23.0661497,
                      "lng" : 77.2369767
                   }
                },
                "location" : {
                   "lat" : 23.2599333,
                   "lng" : 77.412615
                },
                "location_type" : "APPROXIMATE",
                "viewport" : {
                   "northeast" : {
                      "lat" : 23.3326697,
                      "lng" : 77.5748062
                   },
                   "southwest" : {
                      "lat" : 23.0661497,
                      "lng" : 77.2369767
                   }
                }
             },
             "place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
             "types" : [ "locality", "political" ]
          }
       ],
       "status" : "OK"
    }
    

    I shall iterate in below given fashion to "location" : { "lat" : 23.2599333, "lng" : 77.412615

    //recieve JSON in json object

            JSONObject json = new JSONObject(output.toString());
            JSONArray result = json.getJSONArray("results");
            JSONObject result1 = result.getJSONObject(0);
            JSONObject geometry = result1.getJSONObject("geometry");
            JSONObject locat = geometry.getJSONObject("location");
    
            //"iterate onto level of location";
    
            double lat = locat.getDouble("lat");
            double lng = locat.getDouble("lng");
    
    0 讨论(0)
  • 2020-12-02 19:57

    Try this, you can parse nested JSON

    public static String getJsonValue(String jsonReq, String key) {
            JSONObject json = new JSONObject(jsonReq);
            boolean exists = json.has(key);
            Iterator<?> keys;
            String nextKeys;
            String val = "";
            if (!exists) {
                keys = json.keys();
                while (keys.hasNext()) {
                    nextKeys = (String) keys.next();
                    try {
                        if (json.get(nextKeys) instanceof JSONObject) {
                            return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
                        } else if (json.get(nextKeys) instanceof JSONArray) {
                            JSONArray jsonArray = json.getJSONArray(nextKeys);
                            int i = 0;
                            if (i < jsonArray.length()) do {
                                String jsonArrayString = jsonArray.get(i).toString();
                                JSONObject innerJson = new JSONObject(jsonArrayString);
                                return getJsonValue(innerJson.toString(),key);
                            } while (i < jsonArray.length());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                val = json.get(key).toString();
            }
            return val;
        }
    
    0 讨论(0)
  • 2020-12-02 19:59

    You can see that JSONObject extends a HashMap, so you can simply use it as a HashMap:

    JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
    for (Map.Entry in jsonChildOBject.entrySet()) {
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }
    
    0 讨论(0)
  • 2020-12-02 20:00
    JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
        JSONObject secObject = (JSONObject) jsonChildArray.get(1);
    

    I think this should work, but i do not have the possibility to test it at the moment..

    0 讨论(0)
  • 2020-12-02 20:06

    To see all keys of Jsonobject use this

        String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
        JSONObject obj = new JSONObject(JSON);
        Iterator iterator = obj.keys();
        String key = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            System.out.pritnln(key);
        } 
    
    0 讨论(0)
提交回复
热议问题