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.

相关推荐
柳如烟@3 分钟前
docker python:latest镜像 允许ssh远程
python·docker·ssh
bryant_meng7 分钟前
【python】OpenCV—Hough Circle Transform
开发语言·python·opencv·hough·圆形检测
爱的叹息9 分钟前
Java 集合框架中 `List` 接口及其子类的详细介绍,并用 UML 图表展示层次结构关系,用表格对比各个类的差异。
java·list·uml
chen丶223 分钟前
搭建基于flask的web应用框架
python·flask
qzw121037 分钟前
Java与Elasticsearch集成详解,以及使用指南
java·elasticsearch·jenkins
爱的叹息37 分钟前
分别用树型和UML结构展示java集合框架常见接口和类
java·开发语言·uml
马院代表人38 分钟前
Java入职篇(4)——git的使用
java·git·职场和发展
猿六凯1 小时前
历年云南大学计算机复试上机真题
java·华为od·华为
尽力不摆烂的阿方1 小时前
《图解设计模式》 学习笔记
java·笔记·学习·设计模式
梦想画家1 小时前
使用Python Seaborn创建热力图:从核心概念到实战案例
python·信息可视化