在Android中解码带有特定对象的json数组


Decoding a json array with certain objects in Android

因此,我将以下数据作为json响应发送到Android代码中的"client.execute()"方法。

[{"groupId":"26","adminId":"33177","userId":"65515"},{"groupId":"26","adminId":"33177","userId":"95272"},{"groupId":"26","adminId":"33177","userId":"33177"},{"groupId":"1","adminId":"33177","userId":"95272"},{"groupId":"1","adminId":"33177","userId":"47020"}]

用于创建要发送回Android应用程序的json数据的代码如下:

while($k<$i)
{       
    $qr = "SELECT groupId,adminId,userId FROM groupparticipants WHERE groupId='" . $groupId[$k] ."' AND adminId='" . $adminId[$k] . "'";
    $result = mysqli_query($con,$qr);
    while($row = mysqli_fetch_array($result))
    {
        $finalres[$j]["groupId"]=$row['groupId'];
        $finalres[$j]["adminId"]=$row['adminId'];
        $finalres[$j]["userId"]=$row['userId'];
        $j++;
    }
    $k++;
}
    $finaljson = json_encode($finalres);
    echo $finaljson;

我想知道我该如何在安卓系统中解码它。或者有没有更好的代表形式可以发送。

您可以将JSON响应保存为String,然后初始化JSONArray,如下所示:

JSONArray jsonArray = new JSONArray(json);

假设json的值是JSON响应。

然后,您可以从JSONArray中获取每个JSONObject

您的JSON响应看起来解析起来非常简单。我会使用Gson创建一个对象,其中包含您的响应中的三个字段。关于对象列表的解析,请参阅此处的公认答案:

如何使用GSON解码字符串对列表?