How to convert a JSON string to a map using Jackson
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.
- Add the following dependency to the
pom.xmlfile.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0-rc1</version>
</dependency>
- Create an object of the
ObjectMapperclass. - Use the method
readValue()of theObjectMapperclass, 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));}}