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 分钟前
2025-08-09通过授权码的方式给exe程序充值
笔记·python
mortimer11 分钟前
pydub下音频处理:跨越wav格式的4GB限制这道坎
python·ffmpeg·numpy
AI风老师43 分钟前
5、docker镜像管理命令
java·docker·eureka
Dxy12393102161 小时前
Python合并两个PDF文件
python·pdf
用户84913717547161 小时前
JustAuth实战系列(第5期):建造者模式进阶 - AuthRequestBuilder设计解析
java·设计模式·架构
OAFD.1 小时前
Matplotlib 入门到实战:从零开始学 Python 数据可视化
python·信息可视化·matplotlib
WSSWWWSSW1 小时前
Numpy科学计算与数据分析:Numpy广播机制入门与实践
python·数据挖掘·数据分析·numpy
励志成为糕手2 小时前
从反射到方法句柄:深入探索Java动态编程的终极解决方案
java·开发语言
是乐谷2 小时前
饿了么招java开发咯
java·开发语言·人工智能·程序人生·面试·职场和发展
zhysunny2 小时前
20.万物皆可变身术:状态模式架构全景解析
java·状态模式