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.

相关推荐
哥谭居民00011 分钟前
mybatis注册一个自定义拦截器,拦截器用于自动填充字段
java·开发语言·jvm·mybatis
@黄色海岸4 分钟前
【sklearn 05】sklearn功能模块
人工智能·python·sklearn
追逐☞25 分钟前
PyTorch使用-张量类型转换
人工智能·pytorch·python
馨谙25 分钟前
Java中接口隔离原则简介和代码举例
java·接口隔离原则
懒大王爱吃狼33 分钟前
Python + Qt Designer构建多界面GUI应用程序:Python如何调用多个界面文件
开发语言·数据库·python·qt·mysql·python基础·命令模式
北京_宏哥37 分钟前
🔥《手把手教你》系列练习篇之8-python+ selenium自动化测试(详细教程)
前端·python·selenium
iVictor38 分钟前
深入解析 Druid 连接池:连接有效性检测与 Keep-Alive 机制
java
北京_宏哥39 分钟前
🔥《手把手教你》系列练习篇之7-python+ selenium自动化测试(详细教程)
前端·python·selenium
三道杠卷胡1 小时前
【AI News | 20250316】每日AI进展
人工智能·python·语言模型·github·aigc
菜菜的后端私房菜1 小时前
RocketMQ(十一):事务消息如何满足分布式一致性?
java·后端·rocketmq