使用改造,我需要调用一个Api,它会给我一个带有动态字段的json,动态字段会根据我提供的参数而变化。例如,对于“符号”参数“ ETH”,“ XRP”和“转换”参数“ USD”,响应将是以下Json:
<c xmlns:x="x">
<a/>
</c>
我创建了如下ApiClass:
{
"data":{
"ETH":{
"id":1027,
"name":"Ethereum",
"symbol":"ETH",
"quote":{
"USD":{
"price":225.911630584,
"volume_24h":9744372948.14671,
"percent_change_1h":-2.87302,
"percent_change_24h":-4.94698,
"percent_change_7d":-26.9517,
"market_cap":24152563209.793915
}
}
},
"XRP":{
"id":52,
"name":"XRP",
"symbol":"XRP",
"quote":{
"USD":{
"price":0.31390356279,
"volume_24h":1610830847.99846,
"percent_change_1h":-1.37633,
"percent_change_24h":-0.0736244,
"percent_change_7d":-21.4656,
"market_cap":13361806194.547878
}
}
}
}
}
我有这个界面:
public class ApiConstants {
public static String APP_KEY="xxxx-xxxx-xxxx-xxxx";
public static String BASE_URL = "https://pro-api.coinmarketcap.com/";
public static final String CRYPTOCURRENCYQUOTES="v1/cryptocurrency/quotes/latest";
我的改造:
public interface CoinToCoin {
@GET(ApiConstants.CRYPTOCURRENCYINFO)
Call<MainClass...base class that must be created> convertCoinToCoin(@Header("X-CMC_PRO_API_KEY") String appkey,
@Query("symbol") String
coinToCoinConvertedCoinSymbol, @Query("convert") String
coinToCoinSymbol);
}
在我的主要活动中,我必须实例化RetrofitClient
public class RetrofitClient {
private static RetrofitClient instance = null;
private Retrofit retrofit;
private OkHttpClient client;
private CoinToCoin coinToCoin;
private RetrofitClient() {
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
client = okHttpBuilder.build();
retrofit = new Retrofit.Builder().baseUrl(ApiConstants.BASE_URL).addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
coinToCoin= retrofit.create(CoinToCoin.class);
}
public static RetrofitClient getInstance() {
if (instance == null) {
instance = new RetrofitClient();
}
return instance;
}
public CoinToCoin getCoinToCoin() { return coinToCoin;
}
}
,然后打电话检索我需要的数据:
private RetrofitClient retrofit;
retrofit = RetrofitClient.getInstance();
从我发现做到这一点的最佳方法是使用HashMaps和反序列化,但是我不怎么想。 另外,我真的不知道我需要创建的类的外观。
请明确告诉我如何逐步进行操作。向新手求助。
答案 0 :(得分:0)
就我个人而言,我会去找一张你说的地图。根据您的json,您可以为每个硬币定义一个对象:
UTF-8
我不确定数据是否总是相同,但如果不一致,则可以采用类似的方法:
<body onafterprint="myFunction()">
现在,您可以使用public class Quote {
@SerializedName("price")
private double price;
@SerializedName("volume_24h")
private double volume24h;
@SerializedName("percent_change_1h")
private double percentChange1h;
@SerializedName("percent_change_24h")
private double percentChange24h;
@SerializedName("percent_change_7d")
private double percentChange7d;
@SerializedName("market_cap")
private double marketCap;
// getters and setters
}
public class Coin {
@SerializedName("id")
private int id;
@SerializedName("name")
private String name;
@SerializedName("symbol")
private String symbol;
@SerializedName("quote")
private Map<String, Quote> quote;
// getters and setters
}
作为改造界面的响应。