使用GSON反序列化数组内嵌Double数组的JSON时字段为空如何解决
问题原因及解决方案
导致反序列化后字段全空的核心原因及对应修复方法如下:
1. 补充实体类的setter方法
你当前的HistoricalPrices实体类只定义了getter方法,缺少对应setter,部分Gson版本的反序列化逻辑需要通过setter给私有字段赋值,补充代码如下:
public class HistoricalPrices { private List<List<Double>> prices; private List<List<Double>> market_caps; private List<List<Double>> total_volumes; public List<List<Double>> getPrices() { return prices; } public void setPrices(List<List<Double>> prices) { this.prices = prices; } public List<List<Double>> getMarket_caps() { return market_caps; } public void setMarket_caps(List<List<Double>> market_caps) { this.market_caps = market_caps; } public List<List<Double>> getTotal_volumes() { return total_volumes; } public void setTotal_volumes(List<List<Double>> total_volumes) { this.total_volumes = total_volumes; } }
2. 显式指定序列化字段名
给每个字段加上@SerializedName注解,显式和JSON返回的key绑定,避免Gson命名策略冲突导致的匹配失败:
import com.google.gson.annotations.SerializedName; public class HistoricalPrices { @SerializedName("prices") private List<List<Double>> prices; @SerializedName("market_caps") private List<List<Double>> market_caps; @SerializedName("total_volumes") private List<List<Double>> total_volumes; // 后续保留原有的getter+新增的setter即可 }
3. 校验字段是否真的为空
你当前直接打印response.body().toString(),如果没有重写HistoricalPrices的toString方法,输出结果只会是对象的内存地址,无法判断字段是否为空。你可以添加日志打印字段长度验证:
@Override public void onResponse(Call<HistoricalPrices> call, Response<HistoricalPrices> response) { if(!response.isSuccessful()){ return; } HistoricalPrices historicalPrices = response.body(); // 打印数组长度验证是否有值 System.out.println("prices长度:" + historicalPrices.getPrices().size()); System.out.println("market_caps长度:" + historicalPrices.getMarket_caps().size()); System.out.println("total_volumes长度:" + historicalPrices.getTotal_volumes().size()); }
可选优化
数组第一个元素是13位毫秒级时间戳,用Double接收可能存在精度损失,后续可以把字段类型改成List<List<Number>>,或者自定义反序列化器将数组转成时间戳+数值的实体类,提升数据准确性。
内容的提问来源于stack exchange,提问作者AtomicallyBeyond
相关产品推荐
相关产品推荐

