在Json数组中搜索一个值

3

i have the following json response:

{
"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无法转换为org.json.simple.JSONArray”的错误。我认为问题是因为我的json是一个数组,但是如何获取属性呢?

最好的问候!


尝试使用 System.out.println(jsonObject) 查看它实际包含了什么。 - Young Emil
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
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);
这将按预期工作。

1
不是我,但是myResponse的类型应该是JSONArray,对吧? - Jorn Vernee
是的,已经更正了。由于网络问题我正在编辑,这导致它被延迟了,等到有人投反对票的时候! - Pradeep Simha

0
但问题是,我总是得到“org.json.simple.JSONObject无法转换为org.json.simple.JSONArray”。我认为问题是因为我的JSON是一个数组,但我该如何获取属性呢? 使用JSONArray代替。
JSONArray myResponse = jsonObject.getJSONArray("elements");

在这里你可以找到更多的例子


@InfoEngi 很高兴听到您解决了问题,如果您解决了问题,可以点击勾号 V 将答案标记为已接受的答案 http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work - joc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,