【问题标题】:The method getJSONObject(String) is undefined for the type JSONObject方法 getJSONObject(String) 未为 JSONObject 类型定义
【发布时间】: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

【问题讨论】:

标签: java json parsing jsonobject


【解决方案1】:
JSONObject jsonObject = (JSONObject) JSONValue.parse(output);

试试这个。

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

jsonObject.has("key1");

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-09-19
      • 2018-09-18
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多