N-M25
N-M25

Reputation: 49

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

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

Upvotes: 2

Views: 16826

Answers (2)

ecyshor
ecyshor

Reputation: 1439

JSONObject jsonObject = (JSONObject) JSONValue.parse(output);

Try this.

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

jsonObject.has("key1");

Upvotes: 4

Quicksilver002
Quicksilver002

Reputation: 735

You need to parse the object using a parser. Check out the documentation here: https://code.google.com/p/json-simple/wiki/DecodingExamples

Upvotes: 0

Related Questions