2015-03-30 60 views
1

我返回从我的类json方法getJSONObject(字符串)是未定义的类型的JSONObject

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

我怎么能转换outputJSONObject并搜索 “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 
+1

什么库做的JSONObject从何而来?您应该有权访问给定的API并找到将字符串转换为JSONObject对象的方法。 – ecyshor 2015-03-30 19:59:05

+0

你的课堂包装是什么?如果你使用org.json.JSONObject有一个构造函数:http://www.json.org/javadoc/org/json/JSONObject.html – 2015-03-30 19:59:56

+0

我正在使用json-simple-1.1.1.jar。 – 2015-03-30 20:00:19

回答

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

试试这个。

然后你就可以验证使用场的存在:

jsonObject.has("key1"); 
相关问题