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

如何将动态JSON响应中的count与previousCountDay存入HashMap

Alright, let's break down how to take that JSON response and store the count and previousCountDay key-value pairs into HashMaps. I'll cover both Java (since HashMap is a core Java collection) and Python examples, since those are common use cases.

Step-by-Step Solution

Java Approach (Using Jackson Library)

Jackson is a widely used JSON processing library for Java that makes parsing and navigating JSON structures straightforward.

1. Add Jackson Dependency

First, if you're using Maven, add this to your pom.xml to include the library:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- Use the latest stable version available -->
</dependency>

2. Parse JSON and Populate HashMaps

Here's the code to parse your JSON response and fill the HashMaps:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class JsonToHashMap {
    public static void main(String[] args) {
        // Replace this with your actual JSON response string
        String jsonResponse = "{ \"count\": { \"2018-03-28 18\": 55, \"2018-03-28 19\": 48, \"2018-03-28 20\": 41, \"2018-03-28 21\": 31, \"2018-03-28 22\": 32, \"2018-03-28 23\": 26, \"2018-03-29 00\": 20, \"2018-03-29 01\": 16, \"2018-03-29 02\": 12, \"2018-03-29 03\": 0 }, \"previousCountDay\": { \"2018-03-27 18\": 40, \"2018-03-27 19\": 59, \"2018-03-27 20\": 53, \"2018-03-27 21\": 48 } }";

        ObjectMapper mapper = new ObjectMapper();
        HashMap<String, Integer> countMap = new HashMap<>();
        HashMap<String, Integer> previousCountMap = new HashMap<>();

        try {
            // Parse the entire JSON into a navigable JsonNode
            JsonNode root = mapper.readTree(jsonResponse);

            // Process the "count" object
            JsonNode countNode = root.get("count");
            if (countNode != null && countNode.isObject()) {
                Iterator<Map.Entry<String, JsonNode>> entries = countNode.fields();
                while (entries.hasNext()) {
                    Map.Entry<String, JsonNode> entry = entries.next();
                    countMap.put(entry.getKey(), entry.getValue().asInt());
                }
            }

            // Process the "previousCountDay" object
            JsonNode previousNode = root.get("previousCountDay");
            if (previousNode != null && previousNode.isObject()) {
                Iterator<Map.Entry<String, JsonNode>> entries = previousNode.fields();
                while (entries.hasNext()) {
                    Map.Entry<String, JsonNode> entry = entries.next();
                    previousCountMap.put(entry.getKey(), entry.getValue().asInt());
                }
            }

            // Optional: Verify the populated maps
            System.out.println("Count Map: " + countMap);
            System.out.println("Previous Count Map: " + previousCountMap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Key Notes:

  • ObjectMapper converts the JSON string into a JsonNode, which lets us traverse the JSON structure easily.
  • We iterate over each key-value pair in count and previousCountDay, adding them to their respective HashMaps.
  • Use asText() instead of asInt() if your values are strings, or adjust the type based on your actual JSON data.

Python Approach (Using Built-in JSON Module)

Python's built-in json module simplifies this even more, since Python dictionaries are natively equivalent to HashMaps.

Parse JSON and Extract Maps

import json

# Your JSON response as a string
json_response = '''{ "count": { "2018-03-28 18": 55, "2018-03-28 19": 48, "2018-03-28 20": 41, "2018-03-28 21": 31, "2018-03-28 22": 32, "2018-03-28 23": 26, "2018-03-29 00": 20, "2018-03-29 01": 16, "2018-03-29 02": 12, "2018-03-29 03": 0 }, "previousCountDay": { "2018-03-27 18": 40, "2018-03-27 19": 59, "2018-03-27 20": 53, "2018-03-27 21": 48 } }'''

# Parse JSON string into a nested dictionary
data = json.loads(json_response)

# Extract the count and previousCountDay dictionaries directly
count_map = data.get("count", {})
previous_count_map = data.get("previousCountDay", {})

# Optional: Print to verify results
print("Count Map:", count_map)
print("Previous Count Map:", previous_count_map)

Key Notes:

  • json.loads() automatically converts the JSON object into a Python dictionary, so no manual iteration is needed for the inner count and previousCountDay objects.
  • Using get() with an empty dictionary fallback ensures your code doesn't break if the key is missing from the JSON response.

内容的提问来源于stack exchange,提问作者Abhishek kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:54:59