[java] Retrieving values from nested JSON Object

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

{
    "LanguageLevels": {
        "1": "Poczatkujacy",
        "2": "SrednioZaawansowany",
        "3": "Zaawansowany",
        "4": "Ekspert"
    }
}

I want to retrieve value (SrednioZaawansowany) of Key 2 from Language Levels.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonSimpleExample {
public static void main(String[] args) {

JSONParser parser = new JSONParser();

try {

    Object obj = parser.parse(new FileReader("myfile"); 
    JSONObject jsonObject = (JSONObject) obj;
    JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");

What to do next? How I can iterate over it?

This question is related to java json parsing nested

The answer is


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..


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;
    }

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);
    } 

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());
}

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");

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?

Examples related to nested

Nested routes with react router v4 / v5 Extract first item of each sublist python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" How can I combine multiple nested Substitute functions in Excel? Retrieving values from nested JSON Object MySQL Nested Select Query? List comprehension on a nested list? Nested ifelse statement Single Line Nested For Loops Nested or Inner Class in PHP