简体   繁体   English

用Java解析HTTP JSONObject响应

[英]Parse HTTP JSONObject response in java

From the endpoint " test " I am returning a JSONObject : 从端点“ test ”我返回一个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". 在检查返回值的方法中,我想搜索“ 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? 如何解析返回的JSONObject?

Have you tried constructing the JSONObject from its string representation (see http://www.json.org/javadoc/org/json/JSONObject.html ): 您是否尝试过从其字符串表示形式构造JSONObject(请参阅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 json是您从InputStream读取的字符串

Note: you might have to strip the last new line char or even omit new lines altogether 注意:您可能必须删除最后一个新行char甚至完全省略新行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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