Java 如何从JSON文件中获取相对值?

Java 如何从JSON文件中获取相对值?,java,json,get,postman,Java,Json,Get,Postman,我正在尝试从以下JSON文件获取名为Item2的项的testId: { "errors": [], "data": { "collections": [ { "testId": 250, "name": "Item1", "itemCount": 3 }, { "testId": 350, "name": "Item2", "itemCount":

我正在尝试从以下JSON文件获取名为Item2的项的testId

{
  "errors": [],
  "data": {
    "collections": [
      {
        "testId": 250,
        "name": "Item1",
        "itemCount": 3
      },

      {
        "testId": 350,
        "name": "Item2",
        "itemCount": 4
      },
      {
        "testId": 411,
        "name": "Item3",
        "itemCount": 1
      },
      {
        "testId": 450,
        "name": "null",
        "itemCount": 0
      }
    ]
  }
}
这个JSON是我在postman上运行的GET请求的响应

我可以获取这个JSON中任何键的值,但我不能添加像这样的相对条件 正在获取名为Item6的项的testID

我使用数组列表获取所有元素的testID值,这对我来说很好。我能在以下方面做出任何改变以实现我的目标吗

protected String  getTokenValueUnderHierarchy( String responseString) throws ClientProtocolException, IOException {
        String responseRecordsTitle = null;
        List<String> list = Arrays.asList(responseString.split("testId"));
        System.out.println("list.size()::"+list.size());
        for (int i=0;i<list.size();i++){        
            System.out.println("List Element:"+list.get(i));
            responseRecordsTitle = getTokenValue(responseString,"testId");
        }
        return responseRecordsTitle;

    }
受保护的字符串getTokenValueUnderHierarchy(字符串响应字符串)引发ClientProtocolException,IOException{
字符串响应记录字符串=null;
List=Arrays.asList(responseString.split(“testId”);
System.out.println(“list.size()::”+list.size());

对于(int i=0;i您可以使用java可用的JSON解析器。以下是其中之一。当您从JSON数组中检索值时,您可以进行简单的字符串比较以检查条件。!希望有帮助。

我明白了!感谢@Castor的提示。 以下几点对我很有用:

responseJson是作为GET请求的响应而获取的JSON文件

protected int getIdFromArrayOfCollectionItems(String responseJson) throws JSONException{
    int collectionId=0;
    JSONObject root = new JSONObject(responseJson).getJSONObject("data");
    JSONArray collectionArray = root.getJSONArray("collections");
    for(int i =0 ;i<collectionArray.length();i++){
        JSONObject collectionObject = collectionArray.getJSONObject(i);
        String name = collectionObject.getString("name"); 
        if(name.equalsIgnoreCase("Item2")){
            collectionId = collectionObject.getInt("collectionId"); 
            System.out.println("collection ID::"+collectionId);
        }
    }
    return collectionId;

}
protected int getIdFromArrayOfCollectionItems(字符串响应JSON)抛出JSONException{
int collectionId=0;
JSONObject root=新的JSONObject(responseJson).getJSONObject(“数据”);
JSONArray collectionArray=root.getJSONArray(“collections”);

对于(int i=0;iIs)有什么特定的理由来编写自定义逻辑?为什么不能使用此url中显示的现有api始终更好地将json转换为对象以便于维护(将来会有帮助)是的!我需要此逻辑,因为我将获取的ID将用作其他服务请求的url参数。