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.

相关推荐
坐吃山猪5 分钟前
BrowserUse11-源码-LLM模块
python·llm·playwright·browser-use
lang201509286 分钟前
深入解析Java资源加载机制
java·开发语言·python
爱笑的眼睛1140 分钟前
自动机器学习组件的深度解析:超越AutoML框架的底层架构
java·人工智能·python·ai
LCG米43 分钟前
嵌入式Python工业环境监测实战:MicroPython读取多传感器数据
开发语言·人工智能·python
自学小白菜1 小时前
每周刷题 - 第三周 - 双指针专题 - 02
python·算法·leetcode
⑩-1 小时前
简单业务异常类
java
乘风!1 小时前
NSSM启动tomcat部署Java程序
java·服务器·后端·tomcat
BBB努力学习程序设计1 小时前
Java 21虚拟线程与平台线程:JVM层面的深度对比与实现原理
java
代码无疆1 小时前
学点java字节码更易于理解一些特殊的java语法效果
java·后端
BBB努力学习程序设计1 小时前
Java 8日期时间API完全指南:告别Date和Calendar的混乱时代
java