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.

相关推荐
实在智能RPA3 分钟前
航空Agent落地效果评估指标:2026年企业级智能自动化价值度量体系拆解
java·网络·人工智能·ai·自动化
程序员二叉9 分钟前
【JUC】AQS底层深度拆解|独占/共享模式|队列原理全详解
java·开发语言·面试·juc
北极星日淘11 分钟前
Python代理池动态适配日淘爬虫|解决高频抓取IP封禁终极方案(含完整源码)
爬虫·python·tcp/ip
地铁潜行者14 分钟前
消息堆积后,为什么一扩容消费者,MySQL 先被打崩了?
java·后端
地铁潜行者18 分钟前
订单状态更新成功了,分账消息却没发出去:聊聊本地消息表的一致性坑
java·后端
亦暖筑序18 分钟前
Java 8老系统SQL Agent实战:AI生成候选SQL,安全引擎拦截后再执行
java·人工智能·sql
CodeStats19 分钟前
《源纹天书》卷一:归元初醒(第1-5章)
java
大囚长23 分钟前
大模型服务端如何命中缓存
java·人工智能·缓存·dubbo
摇滚侠23 分钟前
SpringMVC 入门到实战 拦截器 78-82
java·后端·spring·maven·intellij-idea
popcorn_min24 分钟前
Breast Cancer 二分类实验:随机森林预测乳腺肿瘤良恶性
python