22

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

{
    "LanguageLevels": {
        "1": "Początkujący",
        "2": "ŚrednioZaawansowany",
        "3": "Zaawansowany",
        "4": "Ekspert"
    }
}

I want to retrieve value (ŚrednioZaawansowany) 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?

1
  • 1
    I suggest to read the official documentation and take a look at their examples if there are some. Commented Jan 3, 2014 at 8:58

7 Answers 7

36

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.

Sign up to request clarification or add additional context in comments.

5 Comments

In constructor of jsonObject Eclipse prints this error: The constructor JSONObject(String) is undefined
@m.aibin Please note that all the files you downloaded from GitHub are not placed in the right package. You must create a new package called org.json then, drap'n'drop all the java files to that package. And you rock!
@m.aibin Also, plz note that, it's not a nested JSON Array, but a nested JSON object. You better change this question's title, it could be misleading.
yes, I used wrong package :) One more question - is it available to get this package from GitHub as a Maven Dependency?? Now I've got it as a package to compile with other my classes
Check this out: mvnrepository.com/artifact/org.json/json. My network speed of linking maven sites is extremely low, so cannot give it a try. But this should be right for your need! ;-)
15

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

Comments

7

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

Comments

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

1 Comment

Note that LanguageLevels is not a JSON Array! Because it starts with a brace, not an open bracket. So your code here may not be appropriate.
1

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

Comments

1

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

Comments

0

Here is an example of retrieving nested JSON object. Department and Product are model classes. Department class holds department as a String and products as ArrayList of Product Product class holds name as a String

depts and products are ArrayList of corresponding model classes

        String jsonDataString = readJSONDataFromFile();
        JSONArray jsonArray = new JSONArray(jsonDataString);

        for (int i=0; i<jsonArray.length(); ++i) {

            JSONObject departmentJSONObject = jsonArray.getJSONObject(i);

            String deptName = departmentJSONObject.getString("department");
            JSONArray productsJSONArray =  departmentJSONObject.getJSONArray("products");

            for (int j =0; j <productsJSONArray.length();j++){
                JSONObject productJSONObject = productsJSONArray.getJSONObject(j);
               String prodName = productJSONObject.getString("name");

                Product product = new Product(prodName);
                products.add(product);
            }
            Department department = new Department(deptName, products);
            depts.add(department);

Here is my raw json file

 [
  {
    "department": "Cold Drink",
    "products": [
      {
        "name": "lemonade",
        "img": "some_url"
      },
      {
        "name": "Oj",
        "img": "some_url"
      }
    ]
  },
  {
    "department": "CD2",
    "products": [
      {
        "name": "lemonade2",
        "img": "some_url2"
      },
      {
        "name": "oj2",
        "img": "some_url2"
      }
    ]
  },
  {
    "department": "CD3",
    "products": [
      {
        "name": "lemonade3",
        "img": "some_url3"
      },
      {
        "name": "oj3",
        "img": "some_url3"
      }
    ]
  }
]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.