You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Java/Android Studio中无需转换为JSON Array获取COVID-19 API返回的JSON Object中dates的最后元素方法咨询

Got it, let's tackle this problem step by step. The dates field in your JSON response is a JSONObject (not a JSONArray) where each key is a date string, and the value holds the COVID data for that day. We can grab the latest entry directly by working with the keys of this JSONObject—no array conversion needed.

Here are two common approaches for Android/Java:

Solution 1: Use Android's built-in org.json library

This is the easiest option since it comes pre-packaged with Android, no extra dependencies required.

Step-by-Step Code

try {
    // Assume you have the full API response stored in responseString
    JSONObject rootJson = new JSONObject(responseString);
    
    // Navigate to the "TT" object and then the "dates" object
    JSONObject ttObject = rootJson.getJSONObject("TT");
    JSONObject datesObject = ttObject.getJSONObject("dates");
    
    // Get all date keys from the dates JSONObject
    Set<String> dateKeys = datesObject.keySet();
    
    // Convert the set to a list to easily access the last element
    List<String> dateList = new ArrayList<>(dateKeys);
    
    // Important: The API returns dates in ascending order (oldest to newest), so the last element is the latest
    if (!dateList.isEmpty()) {
        String latestDate = dateList.get(dateList.size() - 1);
        JSONObject latestCovidData = datesObject.getJSONObject(latestDate);
        
        // Example: Extract total confirmed cases from the latest data
        int totalConfirmed = latestCovidData.getJSONObject("total").getInt("confirmed");
        Log.d("CovidData", "Latest confirmed cases: " + totalConfirmed);
    }
} catch (JSONException e) {
    // Handle parsing errors (e.g., missing keys, invalid JSON)
    e.printStackTrace();
}

If you want to guarantee correct ordering (even if API changes)

If you're worried the API might stop returning dates in order, you can sort the date keys explicitly using LocalDate (requires Android API 26+ or desugaring):

List<String> sortedDates = new ArrayList<>(dateKeys);
Collections.sort(sortedDates, (date1, date2) -> {
    LocalDate d1 = LocalDate.parse(date1);
    LocalDate d2 = LocalDate.parse(date2);
    return d1.compareTo(d2); // Sorts oldest to newest
});

String latestDate = sortedDates.get(sortedDates.size() - 1);

Solution 2: Use Gson library

If your project already uses Gson for JSON parsing, here's how to do it:

Step-by-Step Code

try {
    Gson gson = new Gson();
    JsonObject rootJson = gson.fromJson(responseString, JsonObject.class);
    
    JsonObject ttObject = rootJson.getAsJsonObject("TT");
    JsonObject datesObject = ttObject.getAsJsonObject("dates");
    
    // Using Java 8+ streams to get the latest date (relies on API's ascending order)
    Optional<String> latestDateOpt = datesObject.entrySet().stream()
            .map(Map.Entry::getKey)
            .reduce((first, second) -> second); // Keeps replacing with the next key, ending with the latest
    
    latestDateOpt.ifPresent(latestDate -> {
        JsonObject latestCovidData = datesObject.getAsJsonObject(latestDate);
        int totalConfirmed = latestCovidData.getAsJsonObject("total").get("confirmed").getAsInt();
        Log.d("CovidData", "Latest confirmed cases: " + totalConfirmed);
    });
} catch (JsonSyntaxException e) {
    e.printStackTrace();
}

Important Notes

  • Always wrap your JSON parsing code in try-catch blocks to handle unexpected errors (like missing fields or invalid JSON format).
  • If the dates object could be empty (unlikely with this API), add a check to avoid IndexOutOfBoundsException.

内容的提问来源于stack exchange,提问作者Vishal Anand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:02:49