如何将动态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:
ObjectMapperconverts the JSON string into aJsonNode, which lets us traverse the JSON structure easily.- We iterate over each key-value pair in
countandpreviousCountDay, adding them to their respective HashMaps. - Use
asText()instead ofasInt()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 innercountandpreviousCountDayobjects.- 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
相关产品推荐
相关产品推荐

