【问题标题】:String cannot be converted to int error while retrieving JSON data检索 JSON 数据时字符串无法转换为 int 错误
【发布时间】:2019-02-26 01:22:24
【问题描述】:

这是将从 OkHTTP 接收的 JSON 响应。这只是响应的 10 部分中的一部分。

[{"id":418,"title":{"rendered":"testttt"},"content":{"rendered":"
\n\nThis is a random post trying to implement some feature soon and we 
don\u2019t have any option rather than try in the production environment only. 
Just because this is a stupid decision don\u2019t blame me for this, 
please.\n\n<\/p>\n","protected":false}]

这是我试图获得标题的代码 > 呈现如下:

OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url("http://url.com/wp-json/wp/v2/posts")
            .build();

    Response response = client.newCall(request).execute();
    String myResponse = response.body().string();
    JSONObject json = new JSONObject(myResponse);
    for(int i=0; i <=9 ; i++){
        JSONArray jsonArray = json.getJSONArray("title");
        String title = jsonArray.getString("rendered");
        titles.add(title);
    }

但我收到了这个error: incompatible types: String cannot be converted to int

我不知道我错在哪里。

【问题讨论】:

  • 你会粘贴完整的 logcat 错误吗?您似乎正在尝试将 String 转换为 int,这应该在日志中进行检查。
  • 在我尝试构建和安装应用程序时出现错误。因此,不会生成任何日志。
  • Android Studio 将此错误指向此行String title = jsonArray.getString("rendered");

标签: java android json okhttp


【解决方案1】:

刚刚检查了Json 输出。似乎 title 不是 Array,您将其声明为 Array

JSONArray jsonArray = json.getJSONArray("title");

试试这个:

for(int i=1; i <= json.length(); i++){
        String title = json.getJSONObject(i).getString("rendered");
        titles.add(title);
    }

但是,通过将相同的 Json 输出转换为 GSON POJO,您将能够比旧方法更轻松、更快速地获取数据。

使用:http://www.jsonschema2pojo.org/

还有:Retrieve data using Gson

【讨论】:

  • 现在我在第 233 行遇到 Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 错误,即 for (int i = 0; i &lt; 10; i++) { mList.add(new SlideBean(bgs[i],titlelist[i],icons[i],says[i])); } 。 titlelist[i] 是问题所在。我通过 okhttp 收到了 10 个结果,并使用以下代码添加到标题列表:String[] titlelist = (String[]) titles.toArray(new String[titles.size()]);。对吗???
  • 您已将 i 设置在 0 - 10 之间,这意味着 11 个项目,这就是您收到 ArrayIndexOutOfBoundsException 错误的原因。更新了答案。 Is that Correct??? 恐怕不是。
  • 但我设置了i &lt; 10,这意味着当i 的值等于10 时它会中断。因此,可能的值是 (0-9),表示 10。如果我输入 i &lt;=10,则等于 11。
  • 如何将数组列表titles.add(title)转换为String[] titlelist
  • 您不需要转换它,因为它会将项目添加到适配器中以显示它。哦,很高兴听到帮助。
【解决方案2】:

titles 列表类型,如果intstring

如果是列表类型字符串;

jsonArray.get(i).getString("rendered");

例子:

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
    JSONObject object = array.getJSONObject(n);
    // do some stuff....
}

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 1970-01-01
    • 2020-04-01
    • 2014-12-22
    • 2013-07-24
    • 2011-09-15
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    相关资源
    最近更新 更多