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.

相关推荐
Nice2cu_Code9 分钟前
Python教程(三):类&对象、闭包、装饰器、类型注解、MRO
开发语言·python
databook14 分钟前
manim边学边做--三维图形的场景类
python·动效
调皮的芋头18 分钟前
【“以退为进“、“不得已而为之“与“风险对冲“的协同机制】
python·神经网络·机器学习
杜子腾dd34 分钟前
18.使用读写包操作Excel文件:xlrd、xlwt 和 xlutils 包
python·数据挖掘·excel·numpy·pandas
林泽毅37 分钟前
SwanLab私有化部署教程!
python·深度学习·大模型·强化学习·swanlab·训练实战
Java韩立1 小时前
基于Spring Boot的航司互售系统
java·spring boot·后端
空谷传声~1 小时前
配置blender的python环境
python·blender
东阳马生架构1 小时前
Netty基础—4.NIO的使用简介二
java·网络·netty
陌路物是人非1 小时前
MinIo前后端实现
java·docker·html·minio
字节源流1 小时前
【SpringMVC】常用注解:@ModelAttribute
java·开发语言