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.

相关推荐
悟能不能悟3 分钟前
前端调用a服务,a服务将请求用controller+openfeign调用b服务,接口参数中有header参数和body,a服务应该怎么设置,才简单
java·开发语言·前端
2501_941885963 分钟前
从接口演化到系统自治的互联网工程语法重构与多语言实践思路拆解分享文
java·开发语言
唐叔在学习5 分钟前
才知道python还可以这样发消息提醒的
后端·python·程序员
天天睡大觉6 分钟前
Python学习1
开发语言·python·学习
2501_941805318 分钟前
在阿姆斯特丹智能港口场景中构建集装箱实时调度与高并发物流数据分析平台的工程设计实践经验分享
java·大数据·算法
Johny_Zhao8 分钟前
黑客msfconsole渗透工具超详细使用说明
linux·python·网络安全·信息安全·渗透测试·云计算·系统运维·攻防演练
小许学java8 分钟前
网络原理-HTTP/HTTPS
java·网络·http·https
luoluoal11 分钟前
基于python的旅游景点方面级别情感分析语料库与模型(源码+文档)
python·mysql·django·毕业设计·源码
panamera1212 分钟前
C++ 中 static 关键字
java·开发语言·c++
涂山小楼13 分钟前
线程join()方法的深度理解
java·前端·算法