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 分钟前
基于Spring Boot的网上宠物店系统设计与实现(LW+源码+讲解)
java·前端·spring boot·后端·课程设计
Yoyo25年秋招冲冲冲17 分钟前
Day62_补20250210_图论part6_108冗余连接|109.冗余连接II
java·数据结构·算法·leetcode·深度优先·动态规划·图论
andy7_26 分钟前
Spring中常见的设计模式
java·spring·设计模式
Java-请多指教27 分钟前
更换a.jar包中的lib里的b.jar包里的class文件
java·jar
Strawberry_ahh29 分钟前
MybatisPlus常用增删改查
java·mybatisplus
三皮仔34 分钟前
安装WPS后,导致python调用Excel.Application异常,解决办法
python·excel·wps
兀行者(做个有情怀的java程序员)1 小时前
什么是Java虚拟机(JVM)?它的作用是什么?
java·开发语言·jvm
liberty0307061 小时前
40环状DNA序列的最小表示法Java版-青训营刷题
java·开发语言
java_python源码1 小时前
[含文档+PPT+源码等]精品基于Python实现的django个性化健康餐计划订制系统
开发语言·前端·python
招风的黑耳1 小时前
Java+vue前后端分离项目集群部署
java