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.

相关推荐
喵手2 分钟前
Python爬虫实战:电商问答/FAQ 语料构建 - 去重、分句、清洗,做检索语料等!
爬虫·python·爬虫实战·faq·零基础python爬虫教学·电商问答·语料构建
Dxy12393102163 分钟前
DataFrame条件筛选:从入门到实战的数据清洗利器
python·dataframe
阿在在3 分钟前
Dubbo 消费者是如何与 Spring 融合的?
java·spring·dubbo
金銀銅鐵6 分钟前
浅解 Junit 4 第七篇:AllDefaultPossibilitiesBuilder
java·junit·单元测试
匀泪7 分钟前
云原生(TOMCAT实验)
java·云原生·tomcat
BigGGGuardian7 分钟前
给 Spring Boot 接口加了幂等保护:Token 机制 + 结果缓存,一个注解搞定
java·开源
Kiyra8 分钟前
深入浅出远程连接:Java 后端视角下的底层原理与实践
java·开发语言
一只鹿鹿鹿11 分钟前
数据治理文档(word原件)
java·运维·spring boot·后端
beata11 分钟前
Java基础-12:Java IO深度解析与避坑指南:从底层原理到BIO NIO AIO实战
java·后端
Hx_Ma1611 分钟前
测试题(五)
java·开发语言·后端