How can JSON be converted to a map in Java?

You can use the Jackson library to convert JSON into a Map.

Here is an example code snippet:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

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

        try {
            ObjectMapper objectMapper = new ObjectMapper();

            // 将JSON字符串转换成Map
            Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>(){});

            // 打印Map的内容
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

When running the above code, the output is:

name: John
age: 30
city: New York

In this way, the JSON string is converted into a Map object.

广告
Closing in 10 seconds
bannerAds