Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
jackson
communitycreator

How to convert a JSON string to a map using Jackson

abhilash

In this shot, we will explore how to convert a JSON string to a map in Java.

Jackson is a high-performance JSON processor for Java.

Below are the steps to get a map from a JSON string.

  1. Add the following dependency to the pom.xml file.
<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.0-rc1</version>
</dependency>
  1. Create an object of the ObjectMapper class.
  2. Use the method readValue() of the ObjectMapper class, which takes in a JSON string and the class the string will be converted to.

Method signature

public <T> T readValue(String content, Class<T> valueType)

Parameters

  • String content: JSON string.
  • Class<T> valueType: the class to which the string has to be deserialised to.

Code

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        String s = "{\"name\": \"educative\",\"website\": \"https://www.educative.io/\",\"description\": \"e-learning website\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.readValue(s, Map.class));
    }
}

RELATED TAGS

java
jackson
communitycreator
RELATED COURSES

View all Courses

Keep Exploring