Convert JSON to Java Collection Map using Jackson


Post Banner

In this tutorial, we will see how to convert a JSON String to Java Collection Map Object using Jackson Library,

Make sure you have added the Jackson Dependency in your Gradle/Maven project.

Gradle:

implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.4'

Maven:

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.4</version>
</dependency>

Example: Json String to Java using Jackson Library

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class JsonStringToJavaMap {

    public static void main(String[] args) {
        try {

            String jsonString = "{\n" +
                    "   \"artistName\":\"Michael Jackson\",\n" +
                    "   \"albumName\":\"Thriller\",\n" +
                    "   \"releaseYear\":1982\n" +
                    "}";

            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> map = objectMapper.readValue(jsonString, Map.class);

            System.out.println(map);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Output:

{artistName=Michael Jackson, albumName=Thriller, releaseYear=1982}

Related Post: Convert Java Map to JSON String

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap