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.

相关推荐
HetFrame1 分钟前
大模型驱动的禅道任务自动化规划与创建
python·ai·自动化·大模型·ai编程·任务·禅道
2301_822382761 分钟前
使用Python进行网络设备自动配置
jvm·数据库·python
1104.北光c°3 分钟前
【黑马点评项目笔记 | 优惠券秒杀篇】构建高并发秒杀系统
java·开发语言·数据库·redis·笔记·spring·nosql
ruleslol5 分钟前
普通流(Stream<T>)和原始类型特化流(IntStream, LongStream, DoubleStream)的区别
java
隐退山林5 分钟前
JavaEE初阶:文件操作和IO
java·java-ee
2501_907136826 分钟前
PDF增效工具 Quite imposing plus6
java·开发语言
2501_941982056 分钟前
AI + 企微:使用 Python 接入 DeepSeek/GPT 实现外部群自动技术答疑
人工智能·python·企业微信
Jaxson Lin10 分钟前
Java编程进阶:智能仿真无人机项目3.0
java·笔记·无人机
是阿楷啊11 分钟前
Java求职面试实录:互联网大厂场景技术点解析
java·redis·websocket·spring·互联网·大厂面试·支付系统
jiang_changsheng15 分钟前
MCP协议的核心架构基础
c语言·开发语言·c++·python·comfyui