The method getJSONObject(String) is undefined for the type JSONObject

15,202
JSONObject jsonObject = (JSONObject) JSONValue.parse(output);

Try this.

And then you can verify the existence of the field using:

jsonObject.has("key1");
Share:
15,202
N-M25
Author by

N-M25

Updated on June 04, 2022

Comments

  • N-M25
    N-M25 almost 2 years

    I am returning a json from my class:

    @POST("/test")
        @PermitAll
        public JSONObject test(Map form) {
    
        JSONObject json=new JSONObject();
        json.put("key1",1);
        json.put("key2",2);
            return json;
        }
    

    now I want to get this json from "getInputStream" and parse it to see if key1 exists:

    String output = "";
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    StringBuilder output = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
    }
    
    output=output.toString();
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("output", output);
    
    if (jsonObj.get("output") != null){
        **//search for key1 in output**
        System.out.println("key1 exists");
    }else{
        System.out.println("key1 doesnt exist");
    } 
    reader.close();
    

    How can I convert output to JSONObject and search for "key1"?

    I tried following but I got errors after arrows:

    JSONObject jObject  = new JSONObject(output);  ---> The constructor JSONObject(String) is undefined
    JSONObject data = jObject.getJSONObject("data"); ---> The method getJSONObject(String) is undefined for the type JSONObject
    String projectname = data.getString("name"); ----> The method getString(String) is undefined for the type JSONObject