【发布时间】:2015-03-30 19:52:37
【问题描述】:
我从班级返回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
【问题讨论】:
-
JSONObject 来自什么库?您应该有权访问给定的 API,并找到一种将字符串转换为 JSONObject 对象的方法。
-
你的课包是什么?如果使用 org.json.JSONObject 有一个构造函数:json.org/javadoc/org/json/JSONObject.html
-
我正在使用 json-simple-1.1.1.jar。
-
因此请阅读that library.. 的文档或切换到使用“预期”的 JSON 库来获取所提供的代码。
标签: java json parsing jsonobject