Need to convert a JSON to a Map in Java? First, you’ll need a library for JSON processing.
We will use the Jackson library for this example since it is one of the most used ones in Java. To see where to find Jackson jars, read Introduction to Java JSON.
Let’s say we have a JSON like the following:
{ "key1":"value1", "key2":"value2", "key3":"value3", "key4":"value4", "key5":"value5" }
As you can see, the above JSON is pretty simple. It contains key-value pairs, just like the Map. To convert the above JSON to a Map, we need the ObjectMapper class and the TypeReference, since the Map is a generic type.
Converting a JSON to a Map in Java
Here is the program that parses JSON to a Map:
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; class Test { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); // load the JSON file File file = new File("src/main/resources/json_file.json"); JsonNode json = objectMapper.convertValue(file, JsonNode.class); String jsonString = objectMapper.writeValueAsString(json); Map<String, String> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, String>>() {}); System.out.println(map.get("key1")); } }
Output: value1
Here, we first loaded the file. Then we needed to convert it to a String since the readValue() method accepts String as the first argument. Then, as the second argument, we passed the TypeRef that we need to use to work with generic types.
Let’s say we have the following JSON:
{ "user1":{ "name":"Tom", "city":"London", "state":"UK" }, "user2":{ "name":"Megan", "city":"Tokyo", "state":"Japan" } }
To convert it to a Map, we need the corresponding Java class (POJO).
Here is the complete program:
//POJO class class User { private String name; private String city; private String state; //constructors, getters, setters and toString() method } class Test { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); // load the JSON file File file = new File("src/main/resources/json_file.json"); JsonNode json = objectMapper.readValue(file, JsonNode.class); String jsonString = objectMapper.writeValueAsString(json); Map<String, User> map = objectMapper.readValue(jsonString, new TypeReference<Map<String, User>>() {}); System.out.println(map.get("user1")); } }
Output: User{name=’Tom’, city=’London’, state=’UK’}
The POJO needs to have default constructor, getters, and setters methods for the Jackson conversion. Jackson maps the fields by matching the names of the JSON fields to the getter and setter methods in the Java object.
That’s it!
Happy coding!