To convert a JSONArray to a List<Map<String, String>> in Java

To convert a JSONArray to a List<Map<String, String>> in Java, you can utilize the Jackson library's ObjectMapper for efficient parsing. Here's how you can achieve this:

1. Add Jackson Dependency:

Ensure that the Jackson library is included in your project. If you're using Maven, add the following dependency to your pom.xml:

XML 复制代码
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.17.0</version>
</dependency>

2. Convert JSONArray to List<Map<String, String>>:

Assuming you have a JSON array string, you can parse it as follows:

java 复制代码
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonArrayToListMap {
    public static void main(String[] args) {
        String jsonArray = "[{\"key1\":\"value1\", \"key2\":\"value2\"}, {\"keyA\":\"valueA\", \"keyB\":\"valueB\"}]";
        ObjectMapper mapper = new ObjectMapper();

        try {
            // Convert JSON array string to List<Map<String, String>>
            List<Map<String, String>> list = mapper.readValue(jsonArray, new TypeReference<List<Map<String, String>>>(){});

            // Iterate through the list and print each map
            for (Map<String, String> map : list) {
                System.out.println(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • ObjectMapper: Jackson's ObjectMapper is a powerful tool for converting between Java objects and JSON.

  • TypeReference: The TypeReference is used to define the target type for the conversion. In this case, it's a List<Map<String, String>>.

  • readValue: This method reads the JSON input and converts it into the specified type.

    java 复制代码
    {key1=value1, key2=value2}
    {keyA=valueA, keyB=valueB}

    This approach ensures that your JSON array is accurately converted into a list of maps, with each JSON object represented as a Map<String, String> in the list.

相关推荐
全栈凯哥2 分钟前
18.Python中的导入类完全指南
python
邵奈一5 分钟前
清明纪念·时光信笺——项目运行指南
java·实战·项目
sunwenjian88625 分钟前
Java进阶——IO 流
java·开发语言·python
sinat_2554878135 分钟前
读者、作家 Java集合学习笔记
java·笔记·学习
皮皮林5511 小时前
如何画出一张优秀的架构图?(老鸟必备)
java
百锦再1 小时前
Java 并发编程进阶,从线程池、锁、AQS 到并发容器与性能调优全解析
java·开发语言·jvm·spring·kafka·tomcat·maven
guts3501 小时前
图像篡改数据集下载:COVERAGE、CASIA
python·数据集
森林猿1 小时前
java-modbus-读取-modbus4j
java·网络·python
tobias.b1 小时前
计算机基础知识-数据结构
java·数据结构·考研
2401_879693871 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python