gpt4 book ai didi

java - 循环通过 JSONObject 创建数组 Java

转载 作者:行者123 更新时间:2023-12-02 03:54:05 28 4
gpt4 key购买 nike

我有一个JSONObject格式如下:

[{"ascii_name":"Rio de Janeiro"},{"ascii_name":"Riyadh"},{"ascii_name":"Rome"},{"ascii_name":"Rawalpindi"},{"ascii_name":"Rabat"},{"ascii_name":"Recife"},{"ascii_name":"Ra's Bayrut"},{"ascii_name":"Rajkot"}]

它是使用以下代码创建的:

while($row = $all_cities->fetch_array())
{
$myArray["ascii_name"] = $row["ascii_name"];
$returnArray[] = $myArray;
}
echo json_encode($returnArray);

现在我使用的是Volley任务将其加载到我的 Android 应用程序中。在 onResponse方法我想获取每个城市名称并将其加载到 ArrayList<String> 中使用for环形。这是我现在的代码,但是从 s 开始它就不起作用了是 JSONObject不是JSONArray

@Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
for (int i = 0; i < jsonObject.length(); i++) {
JSONObject a = jsonObject.getJSONObject(i);
....... more code which isn't relevant
}

最佳答案

而不是

    JSONObject jsonObject = new JSONObject(s);

使用

    JSONArray jsonArray = new JSONArray(s);

此外,我认为您在 Volley 中使用 StringRequest 。切换到 Volley 中的 JSONObjectRequest。

关于java - 循环通过 JSONObject 创建数组 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641751/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com