Android JSONObject 如何获得几个 JSONObject 的



我有JSONObject,我想得到8个对象A,B,C...我的 JSON 字符串:

{"比赛":{"A":

[{"team1":"俄罗斯","team2":"法国","时间":"00:00:00","time0_90":"20","得分":"0 : 0","体育场":"马拉卡纳","裁判":"裁判":"ref","group":"A"},{"team1":"葡萄牙","team2":"洪都拉斯","时间":"00:00:00","time0_90":"60","得分":"0 : 2","体育场":","裁判":","组":"A"}]},"成功":1}{"比赛":{"B":[{"team1":"巴西","team2":"西班牙","时间":"00:00:00","time0_90":"3","得分":"1 : 0","体育场":","裁判":","组":"B"}]},"success":1}{"

Matches":{"C":[]},"success":0}{"Matches":{"D":[]},"success":0}{"Matches":{"E":[]},"success":0}{"Matches":{"F":[]},"success":0}{"Matches":{"G":[]},"success":0}{"Matches":{"H":[]},"success":0}
       JSONObject jsonResponse = new JSONObject(jsonResult);
       JSONArray jsonMathes = jsonResponse.optJSONArray("matches"); 
   // ????????

您的响应结构为:

JSONObject
key:value
JSONObject (key: "Matches")
    JSONArray (key: "A")
        JSONObject,
            key:value,
            key:value,
            etc...
        JSONObject

要访问A,请按照以下步骤操作:

  1. 从响应中创建 JSONObject:

    JSONObject jsonResponseObj = new JSONObject(jsonResponse);
    
  2. 获取关键"匹配"的 JSONObject

    JSONObject jsonMatches = jsonResponseObj.getJSONObject("Matches");
    
  3. 此对象包含键"A"的 JSONArray,因此让我们获取该数组:

    JSONArray jsonArrayA = jsonMatches.optJSONArray("A");
    
  4. 对于您的响应,此数组中有 2 个 JSONObject,因此首先,让我们声明并初始化它们:

    //two JSONObjects
    JSONObject[] jsonObjects = new JSONObject[jsonArrayA.length()];
    //go through the array of JSONObjects and fetch them
    for (int i=0; i < jsonObjects.length; i++) {
        jsonObjects[i] = jsonArrayA.getJSONObject(i);
    }
    
    • 您现在在 jsonArrayA 中A为 JSONArray
    • A包含 2 个 JSONObjects,它们位于 jsonObjects[0] 和 josnObjects[1] 中。
    • 如果你想获取这些jsonObjects的内容,只需使用键获取它,例如:

      String team1Obj1 = jsonObjects[0].getString("team1");   // will contain 'Russia'
      String team2Obj2 = jsonObjects[1].getString("team2");   // will contain 'Honduras'
      String stadium1 = jsonObjects[0].getString("stadium");  // will contain 'Maracana'
      

      等。

最新更新