Android中如何用Retrofit 2与Gson建模含动态日期键的JSON数据?
如何用Retrofit 2 + Gson解析动态键的JSON响应(日期作为键)
嘿,我太懂你碰到的这个麻烦了——这种键每天都在变的JSON,用自动生成固定字段的工具肯定行不通。不过别慌,Gson天生就支持处理这种动态键值对的结构,咱们一步步来搞定:
1. 定义适配动态键的数据模型
不用给每个日期都写一个字段,直接用Map<String, Double>来接收bpi里的内容就行,日期是字符串键,价格是Double值,完美匹配:
public class BitcoinPriceResponse { @SerializedName("bpi") private Map<String, Double> bitcoinPriceMap; public Map<String, Double> getBitcoinPriceMap() { return bitcoinPriceMap; } public void setBitcoinPriceMap(Map<String, Double> bitcoinPriceMap) { this.bitcoinPriceMap = bitcoinPriceMap; } }
这里@SerializedName("bpi")是用来和JSON里的字段名对应上,避免命名不一致的问题。
2. 配置Retrofit和Gson
默认的Gson转换器已经能处理Map类型了,所以不需要额外写自定义适配器,正常配置Retrofit就行:
// 构建Retrofit实例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("你的API基础地址") .addConverterFactory(GsonConverterFactory.create()) .build(); // 定义API接口 public interface BitcoinPriceApi { @GET("你的价格接口路径") Call<BitcoinPriceResponse> fetchPast31DaysPrices(); }
3. 解析数据并转换为绘图友好的格式
拿到响应后,你可以把Map转换成一个包含日期和价格的实体类列表,这样排序、绘图都会更方便:
首先先写个简单的实体类:
public class DatePricePair { private String date; private double price; public DatePricePair(String date, double price) { this.date = date; this.price = price; } // Getter方法 public String getDate() { return date; } public double getPrice() { return price; } }
然后在接口回调里处理转换和排序:
BitcoinPriceApi api = retrofit.create(BitcoinPriceApi.class); Call<BitcoinPriceResponse> call = api.fetchPast31DaysPrices(); call.enqueue(new Callback<BitcoinPriceResponse>() { @Override public void onResponse(Call<BitcoinPriceResponse> call, Response<BitcoinPriceResponse> response) { if (response.isSuccessful() && response.body() != null) { Map<String, Double> priceMap = response.body().getBitcoinPriceMap(); List<DatePricePair> priceList = new ArrayList<>(); // 把Map的键值对转成实体类列表 for (Map.Entry<String, Double> entry : priceMap.entrySet()) { priceList.add(new DatePricePair(entry.getKey(), entry.getValue())); } // 按日期排序(确保绘图时顺序正确) Collections.sort(priceList, (pair1, pair2) -> pair1.getDate().compareTo(pair2.getDate())); // 这里就可以把priceList传给你的绘图组件啦! } } @Override public void onFailure(Call<BitcoinPriceResponse> call, Throwable t) { // 处理请求失败的情况,比如打印日志或者提示用户 t.printStackTrace(); } });
4. 进阶:日期格式转换
如果需要把字符串日期转换成LocalDate或者Date对象(方便做日期计算),可以在转换的时候处理:
// 用Java 8的LocalDate示例 DateTimeFormatter dateFormatter = DateTimeFormatter.ISO_LOCAL_DATE; LocalDate parsedDate = LocalDate.parse(entry.getKey(), dateFormatter); // 然后把parsedDate存到DatePricePair里就行
内容的提问来源于stack exchange,提问作者n4rush0
相关产品推荐
相关产品推荐

