Sarthak Sarthak - 2 months ago 6
Java Question

getJSONObject(String) is undefined for the type JSONObject

I have included all the libraries including

jason-simple-1.1.1.jar
,
org.json.20120521.jar
. Still I am facing this error:


getJSONObject(String) is undefined for the type JSONObject


I have read the previous answers on this issue but those did not work in my project.

JSONParser parser = new JSONParser();

try {

Object obj = parser.parse(new FileReader("c:\\google.json"));

JSONObject jsonObject = (JSONObject) obj;
JSONObject getSth = jsonObject.getJSONObject("Youtube Data"); //this line fails


String social = (String) getSth.get("Social media Platform");
System.out.println(social);
}

Answer

Your code isn't working because it's attempting to use a mish-mash of the APIs for json-simple and org.json.

The method getJSONObject(String) is part of the org.json API. The rest of your code uses the json-simple API. It's unfortunate that both libraries have a class named JSONObject. Perhaps this contributes to your confusion.

I don't see the need to have both libraries. Neither depends on the other. As most of your code uses the json-simple API I would recommend removing org.json from your project (unless another library depends on it), and replacing the line

   JSONObject getSth = jsonObject.getJSONObject("Youtube Data"); //this line fails

with

   JSONObject getSth = (JSONObject) jsonObject.get("Youtube Data"); //this line hopefully should work
Comments