检索 JSON 数据时无法将字符串转换为 int 错误
String cannot be converted to int error while retrieving JSON data
这是将从 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
。
我不知道我哪里错了
刚刚检查了 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
titles
列表类型,如果 int
是 string
.
如果列表类型为字符串;
jsonArray.get(i).getString("rendered");
示例:
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}
这是将从 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
。
我不知道我哪里错了
刚刚检查了 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
titles
列表类型,如果 int
是 string
.
如果列表类型为字符串;
jsonArray.get(i).getString("rendered");
示例:
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}