簡體   English   中英

如何從JSON文件獲取相對值?

[英]How to fetch relative values from JSON file?

我正在嘗試從以下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是我在郵遞員上運行的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;

    }

PS:getTokenValue(String,String)是我創建的用於獲取值的函數,它可以正常工作。

您可以為Java提供用戶JSON解析器。 這是其中之一如何在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;

}

當然,我將傳遞項目名稱作為更多動態行為的參數,但是它起作用:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM