我必须每周都赚比特币钱。如果我使用JsonObject,则得到json,但是我不能使用循环来获取所有数据。而且,如果我使用JSONObject,则返回null。拜托,救救我!
这是我的api:
https://api.coindesk.com/v1/bpi/historical/close.json?start=2018-08-01&end=2018-08-19
{"bpi":{"2018-08-01":7603.7488,"2018-08-02":7535.02,"2018-08-03":7415.5613,"2018-08-04":7009.0888,"2018-08-05":7026.9913,"2018-08-06":6937.0738,"2018-08-07":6717.2088,"2018-08-08":6280.58,"2018-08-09":6537.9025,"2018-08-10":6143.305,"2018-08-11":6233.3813,"2018-08-12":6312.8338,"2018-08-13":6252.37,"2018-08-14":6192.3063,"2018-08-15":6270.0425,"2018-08-16":6314.2413,"2018-08-17":6583.2388,"2018-08-18":6395.3525},"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index. BPI value data returned as USD.","time":{"updated":"Aug 19, 2018 13:06:45 UTC","updatedISO":"2018-08-19T13:06:45+00:00"}}
答案 0 :(得分:0)
您可以使用如下所示的解析数据
JSONObject sys = reader.getJSONObject("bpi");
String country = sys.getString("2018-08-01");
如果它是动态的,那么您可以像下面这样使用
JSONObject mainJSONObj=new JSONObject(<json_string>);
// get category JSONObject from mainJSONObj
JSONObject categoryJSONObj=mainJSONObj.getJSONObject("category");
// get all keys from categoryJSONObj
Iterator<String> iterator = categoryJSONObj.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Log.i("TAG","key:"+key +"--Value::"+categoryJSONObj.optString(key);
}
无论如何,您都可以尝试Retrofit&Gson进行解析,使其成为模型并易于解析。
答案 1 :(得分:0)
使用Gson
,只需在模型类中添加以下代码即可。
@SerializedName("bpi")
JsonElement results;
public Map<String, String> getResults() {
Type type = new TypeToken<Map<String, String>>() {}.getType();
final Map<String, String> objects = new Gson().fromJson(results, type);
return objects;
}
这是您的模型类的外观
public class Model {
@SerializedName("disclaimer")
private String disclaimer;
@SerializedName("time")
private Time time;
@SerializedName("bpi")
JsonElement results;
public Map<String, String> getResults() {
Type type = new TypeToken<Map<String, String>>() {}.getType();
final Map<String, String> objects = new Gson().fromJson(results, type);
return objects;
}
public String getDisclaimer() {
return disclaimer;
}
public void setDisclaimer(String disclaimer) {
this.disclaimer = disclaimer;
}
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
public class Time {
@SerializedName("updated")
private String updated;
@SerializedName("updatedISO")
private String updatedISO;
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public String getUpdatedISO() {
return updatedISO;
}
public void setUpdatedISO(String updatedISO) {
this.updatedISO = updatedISO;
}
}
}
这是您的API接口方法
@GET("/v1/bpi/historical/close.json")
Call<Model> getData(@Query("start") String start,@Query("end") String end);