Android解析Strapi返回的以[开头的JSON数组时数据全为默认值怎么办
问题根因排查
所有字段输出默认值,是多个问题叠加导致的,按优先级排查:
- 后端返回的JSON本身是非法格式
参考示例的JSON存在尾随逗号语法错误,Android内置的org.json解析器遇到这种格式会直接抛出异常,catch块捕获后直接跳过所有字段赋值逻辑,字段自然保持初始默认值(String为null、int为0)。
先在Strapi端确认实际返回格式,去掉这类语法错误。Android端要先打印原始响应日志,确认实际收到的内容,不要直接解析:非法JSON示例:
{ "id": 1, "Name": "Banana", "Price": 4.99, // 最后一个属性后多余的逗号不符合JSON语法规范 }String body = response.body() != null ? response.body().string() : ""; Log.d("StrapiResponse", "原始响应: " + body); - 字段类型不匹配
StrapiClass中把price定义为int类型,但JSON里的Price是带小数的浮点数(4.99、5.99),就算JSON格式合法,调用getInt("Price")也会抛出类型转换异常,无法取值。
需要把price的类型改为double,取值时用getDouble("Price")。 - 大概率搞错了Strapi的实际响应结构
主流的Strapi v4版本,列表接口不会直接返回以[开头的纯数组,实际响应结构为:
这种情况下直接用{ "data": [ { "id": 1, "attributes": { "Name": "Banana", "Taste": "Sweet", "Color": "Yellow", "Price": 4.99 } } ], "meta": {} }new JSONArray(body)会抛出类型异常,因为根节点是JSON对象而非数组,根本走不到取值逻辑。 - 缺少空值判断
原代码直接调用response.body().string(),如果请求失败、响应为空,会触发空指针异常,同样被catch块捕获,无法获取有效数据。
修改后的可运行代码
public class StrapiClass { final static String BASE_URL = "http://172.16.0.254:1337/"; String endpoint; String name; String color; String taste; double price; public StrapiClass(String endpoint) { this.endpoint = endpoint; getData(); } public void getData() { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(BASE_URL + endpoint) .get() .build(); try { Response response = client.newCall(request).execute(); // 空值判断避免空指针 if (response.body() == null) { Log.e("Strapi", "响应体为空"); return; } String body = response.body().string(); Log.d("StrapiResponse", "拿到的原始响应: " + body); JSONArray jsonArray; // 兼容两种响应结构:旧版纯数组、v4版包在data字段的对象 if (body.trim().startsWith("[")) { jsonArray = new JSONArray(body); } else { JSONObject rootObj = new JSONObject(body); jsonArray = rootObj.getJSONArray("data"); } JSONObject firstItem = jsonArray.getJSONObject(0); // 兼容v4把业务字段包在attributes里的结构 JSONObject targetData = firstItem.has("attributes") ? firstItem.getJSONObject("attributes") : firstItem; name = targetData.getString("Name"); color = targetData.getString("Color"); price = targetData.getDouble("Price"); taste = targetData.getString("Taste"); } catch (JSONException | IOException e) { e.printStackTrace(); Log.e("Strapi", "解析失败: " + e.getMessage()); } } // getter方法同步调整price的返回类型为double public String getName() { return name; } public String getColor() { return color; } public String getTaste() { return taste; } public double getPrice() { return price; } }
注意事项
- 原代码在子线程发起同步网络请求的逻辑是正确的,不需要调整,不会阻塞主线程。
- 如果需要获取完整的水果列表而非仅取数组第一个元素,可以把单个字段的存储改为
List<Fruit>结构,循环遍历JSONArray转换每个实体,不要只取第一个元素。 - 运行后优先查看日志打印的原始响应内容,根据实际JSON结构调整解析逻辑,不要靠猜测结构写解析代码。
内容的提问来源于stack exchange,提问作者JASIM CHOUHAN
相关产品推荐
相关产品推荐

