You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用GSON在Java中解析Binance K线数组的问题求助

解决Binance K线API返回数据的解析问题(Java)

作为Java新手,你遇到的问题主要是URL格式错误Gson解析类型不匹配,还有数组操作和类型转换的基础问题。我帮你一步步修正代码,同时讲解正确的解析方法。

先说说你代码里的几个关键问题

  • URL中的空格:你的URL里api/v1 /klines多了个空格,这会导致无法正确请求API,必须先把这个空格去掉。
  • Gson解析类型错误:Binance返回的是二维字符串数组,但你用String.class去解析,得到的肯定不是正确的数组结构,应该用String[][].class来匹配。
  • 数组访问与类型转换:即使解析正确,你直接用pairString[1][4]访问的前提是pairString是二维数组;另外这些值是字符串类型,必须转成double才能做加法运算,不然会变成字符串拼接,完全不是你想要的数值求和。
  • 输出格式错误:你用%d输出double类型的结果,这会导致格式异常,应该用%f或者%.8f(适配币价的多小数位精度)。

方案一:直接解析为二维字符串数组(快速测试)

这种方式适合快速验证,直接用Gson把返回的JSON转成String[][],再按需转换数据类型:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import com.google.gson.Gson;

public class BinanceKlineParser {
    public static void main(String[] args) {
        try {
            // 修正URL:去掉v1后面的空格
            URL url = new URL("https://api.binance.com/api/v1/klines?symbol=ETHBTC&interval=1m&limit=5");
            URLConnection urlcon = url.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
            
            String response = br.readLine();
            br.close(); // 记得关闭流,避免资源泄漏
            
            System.out.println("API返回原始数据:");
            System.out.println(response);
            
            // 用Gson解析为二维字符串数组
            Gson gson = new Gson();
            String[][] klines = gson.fromJson(response, String[][].class);
            
            // 计算第一个和第二个K线的收盘价之和(数组索引4对应收盘价)
            if (klines.length >= 2) {
                // 将字符串转成double类型
                double closePrice1 = Double.parseDouble(klines[0][4]);
                double closePrice2 = Double.parseDouble(klines[1][4]);
                double sum = closePrice1 + closePrice2;
                
                // 用%.8f输出,匹配币价的小数精度
                System.out.printf("第一根和第二根K线的收盘价之和:%.8f%n", sum);
            } else {
                System.out.println("API返回的数据不足2条");
            }
            
        } catch (Exception e) {
            // 打印完整异常栈,方便调试问题
            e.printStackTrace();
        }
    }
}

方案二:用自定义类解析(更规范,适合长期维护)

如果你的项目需要长期维护,建议用自定义类映射K线数据,可读性更强,不容易出错。Binance的K线数组每个元素的固定顺序是:

  1. 开盘时间
  2. 开盘价
  3. 最高价
  4. 最低价
  5. 收盘价
  6. 成交量
  7. 收盘时间
  8. 成交额
  9. 成交笔数
  10. 主动买入成交量
  11. 主动买入成交额
  12. 忽略字段

第一步:定义Kline实体类

public class Kline {
    private long openTime;
    private double openPrice;
    private double highPrice;
    private double lowPrice;
    private double closePrice;
    private double volume;
    private long closeTime;
    private double quoteAssetVolume;
    private int tradeCount;
    private double takerBuyBaseAssetVolume;
    private double takerBuyQuoteAssetVolume;
    private String ignore;

    // 构造函数
    public Kline(long openTime, double openPrice, double highPrice, double lowPrice, double closePrice,
                 double volume, long closeTime, double quoteAssetVolume, int tradeCount,
                 double takerBuyBaseAssetVolume, double takerBuyQuoteAssetVolume, String ignore) {
        this.openTime = openTime;
        this.openPrice = openPrice;
        this.highPrice = highPrice;
        this.lowPrice = lowPrice;
        this.closePrice = closePrice;
        this.volume = volume;
        this.closeTime = closeTime;
        this.quoteAssetVolume = quoteAssetVolume;
        this.tradeCount = tradeCount;
        this.takerBuyBaseAssetVolume = takerBuyBaseAssetVolume;
        this.takerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume;
        this.ignore = ignore;
    }

    // Getter方法(按需补充,这里只示例收盘价的Getter)
    public double getClosePrice() {
        return closePrice;
    }

    // 其他Getter和Setter可以自行补充
}

第二步:用Gson解析为List

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class BinanceKlineParserWithClass {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://api.binance.com/api/v1/klines?symbol=ETHBTC&interval=1m&limit=5");
            URLConnection urlcon = url.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
            
            String response = br.readLine();
            br.close();
            
            Gson gson = new Gson();
            // 用TypeToken告诉Gson要解析为List<Kline>类型
            List<Kline> klineList = gson.fromJson(response, new TypeToken<List<Kline>>() {}.getType());
            
            if (klineList.size() >= 2) {
                double sum = klineList.get(0).getClosePrice() + klineList.get(1).getClosePrice();
                System.out.printf("第一根和第二根K线的收盘价之和:%.8f%n", sum);
            } else {
                System.out.println("API返回的数据不足2条");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

额外注意事项

  • 记得引入Gson依赖:如果是Maven项目,在pom.xml中添加以下依赖(用最新稳定版即可):
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>
  • 异常处理尽量不要只打印System.out.println(e),用e.printStackTrace()能看到完整的异常栈,更容易定位问题。

内容的提问来源于stack exchange,提问作者user9830671

火山引擎 最新活动