使用Retrofit获取Google Places API的weekdayText为空,如何设置到TextView?
解决Retrofit解析Google Places API weekdayText为空的问题
你遇到的这个空列表问题,大概率是实体类结构不匹配API返回、请求参数缺失或者序列化配置有问题,我来帮你一步步排查解决:
第一步:核对API返回的JSON结构,调整实体类层级
Google Places API的weekday_text并不是直接在响应根层级,而是嵌套在opening_hours对象里的!比如正常的响应结构大概是这样:
{ "name": "示例地点", "opening_hours": { "weekday_text": [ "周一: 9:00 - 18:00", "周二: 9:00 - 18:00" ] } }
你之前直接在Trip类里声明weekdayText字段,肯定解析不到数据。需要调整实体类结构:
- 先创建
OpeningHours类来对应嵌套的营业时间对象:
public class OpeningHours { @SerializedName("weekday_text") @Expose private List<String> weekdayText; public List<String> getWeekdayText() { return weekdayText; } public void setWeekdayText(List<String> weekdayText) { this.weekdayText = weekdayText; } }
- 然后在
Trip类里添加这个嵌套字段:
public class Trip { @SerializedName("opening_hours") @Expose private OpeningHours openingHours; public OpeningHours getOpeningHours() { return openingHours; } public void setOpeningHours(OpeningHours openingHours) { this.openingHours = openingHours; } }
之后在UpdateUI里这样获取数据:
private void UpdateUI(Trip trip) { if (trip.getOpeningHours() != null && trip.getOpeningHours().getWeekdayText() != null) { // 把列表转成换行分隔的字符串显示 String weekdayContent = String.join("\n", trip.getOpeningHours().getWeekdayText()); mTextViewWeekday.setText(weekdayContent); } else { mTextViewWeekday.setText("暂无营业时间信息"); } }
第二步:检查API请求参数是否包含opening_hours字段
Google Places API默认不会返回所有字段,必须在请求时通过fields参数指定需要的数据。如果你的请求URL里没加&fields=opening_hours(或者包含它的组合,比如&fields=name,opening_hours),API根本不会返回weekday_text相关数据,自然解析出来是空列表。
第三步:验证Retrofit的Gson序列化配置
确保你构建Retrofit时正确配置了Gson转换器,并且没有错误忽略字段:
// 如果用了@Expose注解,要确保Gson配置正确 Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://maps.googleapis.com/maps/api/place/") .addConverterFactory(GsonConverterFactory.create(gson)) .build();
如果你的Gson配置了excludeFieldsWithoutExposeAnnotation,但实体类里的字段没加@Expose,就会被忽略导致解析为空。
第四步:打印API响应,确认数据是否存在
在Retrofit的回调里打印完整响应体,确认返回的JSON里确实有weekday_text:
call.enqueue(new Callback<Trip>() { @Override public void onResponse(Call<Trip> call, Response<Trip> response) { if (response.isSuccessful() && response.body() != null) { // 打印响应体,检查是否包含目标字段 Log.d("API_RESPONSE", new Gson().toJson(response.body())); UpdateUI(response.body()); } else { Log.e("API_ERROR", "请求失败: " + response.message()); } } @Override public void onFailure(Call<Trip> call, Throwable t) { Log.e("API_FAILURE", "网络错误: " + t.getMessage()); } });
如果打印出来的JSON里没有weekday_text,那就要回到第二步检查请求参数了。
另外,把List<Object>改成List<String>会更安全,毕竟weekday_text是字符串数组,避免后续处理时的类型转换问题。
内容的提问来源于stack exchange,提问作者user9272981
相关产品推荐
相关产品推荐

