使用Gson反序列化API返回JSON为Java对象时字段为空的问题
字段全空的根本原因
当前你传入Gson的JSON结构和Weather类的结构完全不匹配:
- 传入的JSON根层级仅存在
weather这个键,对应的值是一个数组,数组的元素才是和Weather类字段(id、main、description、icon)一一匹配的对象 - 你直接将整个根JSON反序列化为
Weather类,Gson会在JSON根层级寻找对应字段,但根层级不存在这些目标字段,因此所有字段都会保持null的默认值。
把传入的JSON结构拆分后可以更清晰看到层级差异:
{ "weather": [ { "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" } ] }
你定义的Weather类,对应的其实是上述结构中数组内层的那个对象,并非整个根级JSON对象。
可落地的解决方案
方案1:新增匹配根结构的包装类(生产环境推荐)
新建对应JSON根层级结构的外层类,将Weather类作为它的成员字段:
class WeatherApiResponse { @SerializedName("weather") private List<Weather> weatherList; public List<Weather> getWeatherList() { return weatherList; } public void setWeatherList(List<Weather> weatherList) { this.weatherList = weatherList; } }
调整Gson解析逻辑,先把整个JSON解析为外层包装类,再从中取出目标对象:
Gson gson = new GsonBuilder().create(); WeatherApiResponse response = gson.fromJson( "{\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}]}", WeatherApiResponse.class ); // 从weather数组中取出第一个Weather对象 Weather weather = response.getWeatherList().get(0); Log.i("[Weather]", "Weather: " + weather.getDescription());
方案2:手动定位JSON片段解析(临时调试适用)
如果不想新增包装类,可以直接通过JSON树解析定位到目标内层对象,再做反序列化:
String jsonStr = "{\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}]}"; // 解析为JSON树结构 JsonObject rootObject = JsonParser.parseString(jsonStr).getAsJsonObject(); // 定位到weather数组的第一个元素 JsonElement targetElement = rootObject.getAsJsonArray("weather").get(0); // 反序列化为Weather对象 Weather weather = gson.fromJson(targetElement, Weather.class);
额外说明
你代码中使用的@Expose注解在当前的Gson初始化逻辑下不会导致字段为空:
@Expose注解仅在调用new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()时生效,用来过滤没有标注该注解的字段- 你当前创建Gson实例时没有开启这个过滤开关,因此即使去掉
@Expose注解,只要字段名和JSON key匹配(或通过@SerializedName指定映射关系),Gson依然可以正常访问私有字段完成赋值 - 另外Gson本身支持通过反射直接访问私有字段完成赋值,不依赖类的setter/getter方法,所以类中的访问方法缺失也不会导致字段为空。
内容的提问来源于stack exchange,提问作者Alp4ga
相关产品推荐
相关产品推荐

