How to convert a JsonObject to a HashMap in Java?

In Java, you can use the Jackson library to convert a JSONObject to a HashMap. Here is a simple example:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将JSON字符串转换为JsonNode对象
            JsonNode jsonNode = objectMapper.readTree(json);

            // 将JsonNode转换为HashMap
            HashMap<String, Object> hashMap = convertJsonNodeToHashMap(jsonNode);

            // 打印HashMap
            for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static HashMap<String, Object> convertJsonNodeToHashMap(JsonNode jsonNode) {
        HashMap<String, Object> hashMap = new HashMap<>();

        Iterator<Map.Entry<String, JsonNode>> iterator = jsonNode.fields();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonNode> entry = iterator.next();
            String key = entry.getKey();
            JsonNode value = entry.getValue();

            // 处理嵌套的JsonNode
            if (value.isObject()) {
                hashMap.put(key, convertJsonNodeToHashMap(value));
            } else {
                hashMap.put(key, value.asText());
            }
        }

        return hashMap;
    }
}

The above code utilizes the ObjectMapper class from the Jackson library to convert a JSON string into a JsonNode object. Then, it uses a recursive method called convertJsonNodeToHashMap to transform the JsonNode object into a HashMap object. This method iterates through the fields of the JsonNode and processes the corresponding values based on their types.

Please note that before using the above code, it is necessary to import the Jackson library dependency.

bannerAds