簡體   English   中英

用Java解析HTTP JSONObject響應

[英]Parse HTTP JSONObject response in java

從端點“ test ”我返回一個JSONObject

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

在檢查返回值的方法中,我想搜索“ 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
    }

如何解析返回的JSONObject?

您是否嘗試過從其字符串表示形式構造JSONObject(請參閱http://www.json.org/javadoc/org/json/JSONObject.html ):

JSONObject result = new JSONObject(json)

json是您從InputStream讀取的字符串

注意:您可能必須刪除最后一個新行char甚至完全省略新行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM