C++解析Coingecko API JSON触发未处理异常,加密货币排序失败
加密货币市值排序时nlohmann::json抛出类型错误异常问题
我尝试根据市值排名对用于交易的加密货币vector进行排序,代码编译正常但运行时抛出错误码3的异常。调试发现json.hpp抛出未处理异常:
Unhandled exception at 0x0000500000000000 in MyProgram.exe: Microsoft C++ exception: nlohmann::json_abi_v3_11_2::detail::type_error at memory location 0x000000E000000000.
触发异常的代码行:
JSON_THROW(type_error::create(302, concat("type must be number, but is ", j.type_name()), &j));
需求:通过API获取市值排名后,将加密货币vector按市值从高到低排序并输出到终端。相关代码如下:
trading.h
#ifndef TRADING_H #define TRADING_H #include <string> #include <iostream> #include <vector> using namespace std; class trading{ private: vector<string> coins; public: trading(); void order(); void listOrder(); }; #endif
trading.cpp
#include <string> #include <iostream> #include <vector> #include <cpr/cpr.h> #include <nlohmann/json.hpp> #include "trading.h" // 简化命名 using json = nlohmann::json; using namespace cpr; using namespace std; // 按市值从1到20升序排列加密货币 void trading::order(){ // 变量定义 vector<string> coinsCopy; int rankOrder = 0; // 按市值排序加密货币 string base = "https://api.coingecko.com/api/v3/search?query="; string id; // 复制coins向量 for (int k = 0; k < coins.size(); k++) { coinsCopy.push_back(coins[k]); } for (int i = 0; i < coins.size(); i++) { // 循环变量 string id = coins[i]; auto search = Get(Url{ base + id }); json data = json::parse(search.text); // 获取排名 for (json& item : data["coins"]) { rankOrder = item["market_cap_rank"]; if (rankOrder > coins.size()) { rankOrder = coins.size(); } break; } // 更新coinsCopy到正确的排名位置 coinsCopy.at(rankOrder) = coins[i]; } // 将排序后的结果更新到主coins向量 for (int ii = 0; ii < coins.size(); ii++) { coins.at(rankOrder) = coinsCopy[ii]; } } void trading::listOrder() { for (int j = 0; j < coins.size(); j++) { cout << "排名 #" << j << ": " << coins[j] << endl; } }
Main.cpp
#include <cpr/cpr.h> #include <iostream> #include <nlohmann/json.hpp> #include <string> #include <vector> #include "trading.h" // 简化命名 using json = nlohmann::json; using namespace cpr; using namespace std; int main() { trading trade; trade.order(); trade.listOrder(); }
API返回JSON示例
{"coins":[{"id":"bitcoin","name":"Bitcoin","api_symbol":"bitcoin","symbol":"BTC","market_cap_rank":1,"thumb":"https://assets.coingecko.com/coins/images/1/thumb/bitcoin.png","large":"https://assets.coingecko.com/coins/images/1/large/bitcoin.png"},
初始Coins Vector内容
排名 # 0: bitcoin 排名 # 1: ethereum 排名 # 2: tether 排名 # 3: binancecoin 排名 # 4: usd-coin 排名 # 5: binance-usd 排名 # 6: ripple 排名 # 7: dogecoin 排名 # 8: cardano 排名 # 9: matic-network 排名 # 10: polkadot 排名 # 11: staked-ether 排名 # 12: shiba-inu 排名 # 13: okb 排名 # 14: litecoin 排名 # 15: dai 排名 # 16: tron 排名 # 17: solana 排名 # 18: uniswap 排名 # 19: avalanche-2
内容的提问来源于stack exchange,提问作者John Doe
相关产品推荐
相关产品推荐

