简体   繁体   中英

Parse HTTP JSONObject response in java

From the endpoint " test " I am returning a JSONObject :

@POST("/test")
    @PermitAll
    public JSONObject test(String name) {
    JSONObject jsonval=new JSONObject();
    json.put("key1",true);
    json.put("key2","test");
        return json;
    }

in the method that checks the returned value I want to search for value of "key1".

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String json = null;
    String res = "";

    while ((res = in.readLine()) != null) {
        json += res + "\n";
        }
    in.close();

    if (jsonData has key1 with value true){
    //do sth
    }
    else{
    //do sth else
    }

How can I parse the returned JSONObject?

Have you tried constructing the JSONObject from its string representation (see http://www.json.org/javadoc/org/json/JSONObject.html ):

JSONObject result = new JSONObject(json)

where json is the string you've read from the InputStream

Note: you might have to strip the last new line char or even omit new lines altogether

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM