未为 JSONObject 类型定义方法 getJSONObject(String)

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

我要从我的 class:

返回一个 json
@POST("/test")
    @PermitAll
    public JSONObject test(Map form) {

    JSONObject json=new JSONObject();
    json.put("key1",1);
    json.put("key2",2);
        return json;
    }

现在我想从“getInputStream”中获取这个 json 并解析它以查看 key1 是否存在:

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();

如何将 output 转换为 JSONObject 并搜索 "key1"?

我尝试了以下操作,但在箭头后出现错误:

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

您需要使用解析器解析对象。在此处查看文档:https://code.google.com/p/json-simple/wiki/DecodingExamples

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

试试这个。

然后您可以使用以下方法验证该字段是否存在:

jsonObject.has("key1");