Android Studio使用Retrofit请求ArcGIS API返回空或0值问题咨询
问题排查与解决方案
核心问题梳理
- 实体类结构与接口返回格式完全不匹配:你请求的接口返回的是标准GeoJSON格式,所有业务字段都嵌套在
features数组下每个元素的properties节点中,你当前直接将业务字段定义在根实体类apiData中,Gson解析时找不到对应字段,就会返回基础类型默认值0、引用类型默认值null。 - 请求参数与实体类字段注解不匹配:你在
@GET注解中声明的年龄组字段为Åldersgrupp2,但实体类@SerializedName注解写的是Åldersgrupp,二者不一致会导致年龄组字段解析失败。 - 基础类型的默认值干扰排查:你将统计字段定义为
int基础类型,即便解析失败也会返回默认值0,无法区分是接口真的返回0还是解析失败。
修复步骤
1. 重构实体类匹配GeoJSON结构
首先定义三层实体类匹配返回结构:
根节点实体类
public class ApiRoot { private List<Feature> features; public List<Feature> getFeatures() { return features; } }
Feature节点实体类
public class Feature { private Properties properties; public Properties getProperties() { return properties; } }
业务字段实体类
public class Properties { @SerializedName("Totalt_antal_avlidna") private Integer death; @SerializedName("Totalt_antal_fall") private Integer cases; @SerializedName("Totalt_antal_intensivvårdade") private Integer hospital; // 与请求参数中的outFields保持一致 @SerializedName("Åldersgrupp") private String ageGroup; public Integer getDeath() { return death; } public Integer getCases() { return cases; } public Integer getHospital() { return hospital; } public String getAgeGroup() { return ageGroup; } }
2. 修正请求接口定义
修改返回值类型、修正请求参数中的字段名:
public interface apiCall { // 修正年龄组字段名与实体类注解一致 @GET("4/query?f=geojson&where=1%3D1&outFields=Åldersgrupp&outFields=Totalt_antal_fall&outFields=Totalt_antal_avlidna&outFields=Totalt_antal_intensivvårdade") Call<ApiRoot> getData(); }
3. 修正请求解析逻辑
调整解析逻辑遍历所有分组数据:
//retrofit builder Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://services5.arcgis.com/fsYDFeRKu1hELJJs/arcgis/rest/services/FOHM_Covid_19_FME_1/FeatureServer/") .addConverterFactory(GsonConverterFactory.create()) .build(); //interface apiCall callApi = retrofit.create(apiCall.class); Call<ApiRoot> call = callApi.getData(); call.enqueue(new Callback<ApiRoot>() { @Override public void onResponse(Call<ApiRoot> call, Response<ApiRoot> response) { if(!response.isSuccessful()){ test.setText("code " + response.code()); return; } ApiRoot root = response.body(); if(root == null || root.getFeatures() == null) { test.setText("无有效返回数据"); return; } // 遍历所有年龄组数据 for(Feature feature : root.getFeatures()) { Properties data = feature.getProperties(); String content = ""; content += "age group: " + data.getAgeGroup() +"\n"; content += "cases: " + data.getCases() +"\n"; content += "death: " + data.getDeath() +"\n"; content += "hospital: " + data.getHospital() +"\n\n"; test.append(content); } } @Override public void onFailure(Call<ApiRoot> call, Throwable t) { test.setText(t.getMessage()); } });
额外排查建议
后续遇到类似解析问题,可以先将接口返回的JSON字符串复制出来,用Android Studio的GsonFormat插件自动生成实体类,避免手写结构错漏。
内容的提问来源于stack exchange,提问作者Oliver Gustafsson
相关产品推荐
相关产品推荐

