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



Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.