![](/img/trans.png)
[英]Android Model for JSON parsing shows ClassCastException: com.google.gson.JsonObject can not be casted to com.google.gson.JsonArray
[英]com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray in Java
我正在嘗試使用GSON將“率”放入JsonArray中,但是它不起作用,有人可以建議如何將這個JSon放入Map中,或者使用Java中的Gson將數組或類似的東西?
{
"success": true,
"timestamp": 1548277447,
"base": "USD",
"date": "2019-01-23",
"rates": {
"AED": 3.673021,
"ARS": 37.537301,
"AUD": 1.400099,
"BGN": 1.717902,
"BRL": 3.7657,
"BWP": 10.52802,
"CAD": 1.334645,
"CHF": 0.994703,
"CLP": 671.898015,
"CNY": 6.791896,
"COP": 3151.5,
"DKK": 6.559594,
"EGP": 17.891044,
"EUR": 0.878542,
"GBP": 0.76529,
"HKD": 7.84525,
"HRK": 6.530898,
"HUF": 279.43017,
"ILS": 3.673794,
"INR": 71.13502,
"ISK": 120.350185,
"JPY": 109.595496,
"KRW": 1126.589831,
"KZT": 378.239562,
"LKR": 182.190238,
"LTL": 2.95274,
"LVL": 0.60489,
"LYD": 1.390468,
"MXN": 19.0361,
"MYR": 4.13696,
"NOK": 8.56596
}
}
編輯:添加代碼
HttpURLConnection fixerConnection = (HttpURLConnection) url.openConnection();
fixerConnection.setRequestMethod("GET");
BufferedReader jsonData = new BufferedReader(new InputStreamReader(fixerConnection.getInputStream()));
JsonObject allData = new JsonParser().parse(jsonData).getAsJsonObject();
JsonArray jArray = allData.getAsJsonArray("rates");//getAsJsonObject("symbol");
您將在此處獲得此行的例外情況:
JsonArray jArray = allData.getAsJsonArray("rates");
因為你可以在你輸入文件速率看到的是一個JSON對象不是一個JSON陣列。 讓我告訴你語法上的區別:
"rates": { "AED": 3.673021, "ARS": 37.537301}
"rates": [ {"AED": 3.673021}, {"ARS": 37.537301}]
在第二種情況下,您可以將其作為JSON對象的JSON數組獲得! 我建議閱讀JSON W3教程的DataTypes
好的,現在解決方案是將輸入中的所有內容作為JSON對象提取
HttpURLConnection fixerConnection = (HttpURLConnection) url.openConnection();
fixerConnection.setRequestMethod("GET");
BufferedReader jsonData = new BufferedReader(new
InputStreamReader(fixerConnection.getInputStream()));
JsonObject allData = new JsonParser().parse(jsonData).getAsJsonObject();
// Now Take Rates as JSON Object and capture it in a Map.
JsonObject rates = allData.getAsJsonObject("rates");
Set<Map.Entry<String, JsonElement>> entries = rates.entrySet();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.