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.

相关推荐
梦想不只是梦与想12 小时前
环境管理系统:Conda(一)
python·conda·环境隔离
五仁火烧12 小时前
大模型开发: MCP
java·大模型·mcp
yuzhiboyouye12 小时前
XML写接口适用场景举例
java·服务器·前端
今天的接口写完了吗?12 小时前
Java 使用 OkHttp 调用外部接口
java
yuzhiboyouye12 小时前
零sql和xml写接口,的区别是什么,过程是什么,举例一下下,用mybatis-plus+ spring-boot
java·服务器·前端
计算机源码社12 小时前
基于K-Means聚类的新生儿败血症临床分型与可视化分析系统 基于数据挖掘的新生儿败血症生命体征时序走势与关联性可视化研究
大数据·hadoop·python·数据挖掘·数据分析·spark·毕业设计
一阵寒风12 小时前
用 AI 把PCB制前工程CAM无人值守输出系统做出来
python·ai编程·pcb工艺
小王师傅6613 小时前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
SamChan9013 小时前
Python 处理小语种 PDF 的编码坑:重音字符、连字与 (cid:xx) 乱码的解决方案
python·ai·pdf·机器翻译
量化吞吐机13 小时前
会写代码之后,量化学习还要补上交易判断
人工智能·python