java 未定义 JSONObject 类型的方法 getJSONObject(String)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29355038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The method getJSONObject(String) is undefined for the type JSONObject
提问by N-M25
I am returning a json
from my class:
我正在json
从我的班级返回一个:
@POST("/test")
@PermitAll
public JSONObject test(Map form) {
JSONObject json=new JSONObject();
json.put("key1",1);
json.put("key2",2);
return json;
}
now I want to get this json from "getInputStream
" and parse it to see if key1
exists:
现在我想从“ 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();
How can I convert output
to JSONObject
and search for "key1"?
我怎么能转换output
到JSONObject
,搜索“KEY1”?
I tried following but I got errors after arrows:
我尝试了以下操作,但在箭头后出现错误:
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
回答by ecyshor
JSONObject jsonObject = (JSONObject) JSONValue.parse(output);
Try this.
试试这个。
And then you can verify the existence of the field using:
然后您可以使用以下方法验证该字段的存在:
jsonObject.has("key1");
回答by Quicksilver002
You need to parse the object using a parser. Check out the documentation here: https://code.google.com/p/json-simple/wiki/DecodingExamples
您需要使用解析器来解析对象。在此处查看文档:https: //code.google.com/p/json-simple/wiki/DecodingExamples