我想了解更多关于android的知识,并想要创建一个应用程序来跟踪加密货币的价格。我选择了这个API:https://www.cryptocompare.com/api/#introduction
我的问题如下:当我想得到所有硬币的列表时,JSON响应如下所示:
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"42": {
"Id": "4321",
"Url": "/coins/42/overview",
"ImageUrl": "/media/19984/42.png",
"Name": "42",
"CoinName": "42 Coin",
"FullName": "42 Coin (42)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"FullyPremined": "0",
"TotalCoinSupply": "42",
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "34"
},
"365": {
"Id": "33639",
"Url": "/coins/365/overview",
"ImageUrl": "/media/352070/365.png",
"Name": "365",
"CoinName": "365Coin",
"FullName": "365Coin (365)",
"Algorithm": "X11",
"ProofType": "PoW/PoS",
"FullyPremined": "0",
"TotalCoinSupply": "2300000000",
"PreMinedValue": "299000000",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "916"
},(以下是我使用的URL (https://www.cryptocompare.com/api/data/coinlist/)
我想保存关于硬币的所有信息(所有来自“数据”的信息),但关键并不相同。
我怎样才能得到这些信息来创建我的不同硬币?
预先感谢
发布于 2017-08-18 17:45:11
您可以使用JSONObject#names()作为JSONArray获取所有键,并循环JSONArray。
JSONObject data = response.getJSONObject("Data");
JSONArray array = data.names(); // contains all the keys inside Data
// now loop the array
for (int i = 0; i < array.length(); i++ ) {
String key = array.getString(i); // 42 or 365 for your example code
JSONObject obj = data.getJSONObject(key); // contains the JSONObject of the key 42 or 365
}另一种方法是使用JSONObject#keys(),但它使用Iterator和hasNext()进行迭代,这比在Android中使用上述普通的for循环方法的性能效率要低。
发布于 2017-08-18 19:39:24
接受的答案很好。我想展示从JSON中使用葛森进行解析的方法。下面是如何使用Gson解析它。
你需要上两节课。
这是你的APIResponse.java
public class APIResponse {
public String Response;
public String Message;
public String BaseImageUrl;
public String BaseLinkUrl;
public HashMap<String, DataObject> Data;
}而且DataResponse类应该看起来像
public class DataObject {
public String Id;
public String Url;
public String ImageUrl;
public String Name;
public String CoinName;
public String FullName;
public String Algorithm;
public String ProofType;
public String FullyPremined;
public String TotalCoinSupply;
public String PreMinedValue;
public String TotalCoinsFreeFloat;
public String SortOrder;
}现在很容易。
Type type = new TypeToken<APIResponse>(){}.getType();
APIResponse response = new Gson().fromJson(yourJsonString, type);现在迭代HashMap以获取键和相应的值。
发布于 2017-08-18 17:54:05
您可以获取所有的键并按下面的方式迭代
try {
JSONObject dataObj = obj.getJSONObject("Data"); //obj is the parent json object.
Iterator<?> keys = dataObj.keys();
while(keys.hasNext()) {
JSONObject coinObj = dataObj.getJSONObject(keys.next().toString());
}
} catch (JSONException e) {
e.printStackTrace();
}https://stackoverflow.com/questions/45762012
复制相似问题