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.

相关推荐
goTsHgo3 分钟前
Java的对象头:原理与源码详解
java·开发语言
hie988943 分钟前
如何配置 Java 安全管理器来避免访问控制异常
java·python·安全
wgc2k19 分钟前
Java游戏服务器开发流水账(2)开发中Maven的管理
java·服务器·游戏
LUCIAZZZ19 分钟前
ElasticSearch基本概念
java·大数据·elasticsearch·搜索引擎·中间件·操作系统
冼紫菜25 分钟前
如何使用责任链模式优雅实现功能(滴滴司机、家政服务、请假审批等)
java·开发语言·设计模式·责任链模式
ValidationExpression41 分钟前
设计模式-策略模式
python·设计模式·策略模式
love530love1 小时前
好消息!PyCharm 社区版现已支持直接选择 WSL 终端为默认终端
linux·ide·人工智能·windows·python·pycharm
Uranus^1 小时前
Spring AI 入门(持续更新)
java·人工智能·spring·ai
西柚小萌新1 小时前
【Python从入门到精通】--‘@‘符号的作用
开发语言·python
moxiaoran57531 小时前
Python学习笔记--Django的安装和简单使用(一)
笔记·python·学习