在Java中,com.google.gson.JsonObject不能强制转换为com.google.gson.JsonArray

在Java中,com.google.gson.JsonObject不能强制转换为com.google.gson.JsonArray,java,json,gson,Java,Json,Gson,我试图使用GSON将“rates”放在JsonArray中,但它不起作用,有人能建议如何在Java中使用GSON将这个JSon放在映射、数组或类似的东西中吗 { "success": true, "timestamp": 1548277447, "base": "USD", "date": "2019-01-23", "rates": { "AED": 3.673021, "ARS": 37.537301, "AUD": 1.400099, "

我试图使用GSON将“rates”放在JsonArray中,但它不起作用,有人能建议如何在Java中使用GSON将这个JSon放在映射、数组或类似的东西中吗

{
  "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数组。让我向您展示语法上的差异:

1.按JSON对象进行评级(如您的情况): 2.按JSON数组进行排序: 在第二种情况下,您可以将其作为JSON对象的JSON数组!我建议阅读

好的,现在解决方案是将输入中的所有内容提取为JSON对象

HttpURLConnection fixerConnection=(HttpURLConnection)url.openConnection();
setRequestMethod(“GET”);
BufferedReader jsonData=新的BufferedReader(新的
InputStreamReader(fixerConnection.getInputStream());
JsonObject allData=new JsonParser().parse(jsonData.getAsJsonObject();
//现在将速率作为JSON对象,并将其捕获到映射中。
JsonObject rates=allData.getAsJsonObject(“rates”);
Set entries=rates.entrySet();

请在上面给出错误的那一行共享不起作用的代码。另外,最后一行给出了一个错误。Json来自一个API,我将它放在一个缓冲读取器中。与其将其存储为
,不如将其存储在
映射
中。
"rates": { "AED": 3.673021, "ARS": 37.537301}
"rates": [ {"AED": 3.673021}, {"ARS": 37.537301}]
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();