【问题标题】:Searching a Value in Json Array在 Json 数组中搜索值
【发布时间】:2016-08-31 11:43:49
【问题描述】:

我有以下 json 响应:

{
"elements":
[
    {
        "id": "1234",
        "Key": "1234-name2",  
         "name": "name2",
        "projectName": "TestProject",      
    },
    {
        "id": "5678",
        "applicationKey": "5678-name2",
        "name": "name2",
        "projectName": "TestProject2",
    },
   {
        "id": "9101112",
        "applicationKey": "9101112-name3",
        "name": "name3",
        "projectName": "TestProject3",
    },
],
"totalSize": 3
}

得到响应后,我已将其转换为字符串:

    String PaListContent = getContent(PaListResponse);

    private static String getContent(HttpResponse response) {
        HttpEntity entity = response.getEntity();
        if (entity == null) return null;
        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line = reader.readLine();
            reader.close();
            return line;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

现在,我想在字符串中搜索一个项目名称(例如“Testproject2”),并希望同时拥有属性“id”和“name”。

我试过了

JSONObject jsonObject = new JSONObject(PaListContent);
JSONObject myResponse = jsonObject.getJSONObject("elements");
//JSONArray tsmresponse = (JSONArray) myResponse.get("listTsm");

ArrayList<String> list = new ArrayList<String>();

for(int i=0; i<tsmresponse.length(); i++){
    list.add(tsmresponse.getJSONObject(i).getString("name"));
}

System.out.println(list);

但问题是,我总是得到“org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray”。我认为问题是,因为我的 json 是一个数组,但是我怎样才能获得属性呢?

最好的问候!

【问题讨论】:

  • 试试System.out.println(jsonObject)看看它到底包含什么

标签: java json parsing


【解决方案1】:

您的elements 是一个 JSONArray,但您正试图将其解析为 JSONObject,请像这样更改您的代码:

JSONObject jsonObject = new JSONObject(PaListContent);
JSONArray myResponse = jsonObject.getJSONArray("elements");
//JSONArray tsmresponse = (JSONArray) myResponse.get("listTsm");

ArrayList<String> list = new ArrayList<String>();

for(int i=0; i<myResponse.length(); i++){
    list.add(myResponse.getJSONObject(i).getString("name"));
}

System.out.println(list);

这将按预期工作

【讨论】:

  • 不是我,但是myResponse的类型应该是JSONArray吧?
  • 是的,已更正,由于网络问题,我正在编辑,但在有人投反对票时它被延迟了!
【解决方案2】:

但问题是,我总是得到 org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray。我认为问题是,因为我的 json 是一个数组,但是 我怎样才能获得属性?

改用JSONArray

JSONArray myResponse = jsonObject.getJSONArray("elements");

Here你可以找到更多的例子

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2023-02-24
相关资源
最近更新 更多