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!

Top Hashtags:

Advertisements

Advertisements




Advertisements