Convert JSON to/from Map using Jackson library in Java?

JavaJSONObject Oriented ProgrammingProgramming

The JSON Jackson is a library for Java and it has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. We can convert JSON to/from Map using readValue() and writeValueAsString() methods of com.fasterxml.jackson.databind.ObjectMapper class.

JSON to Map

Syntax

public <T> T readValue(String content, TypeReference valueTypeRef) throws IOException, JsonParseException, JsonMappingException

Example

import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
public class ConvertJSONToMapTest {
   public static void main(String args[]) {
      try {
         ObjectMapper mapper = new ObjectMapper();
         String jsonString = "{\"Name\":\"Raja\", \"Technology\":\"Java\"}";
         Map<String, Object> jsonMap = new HashMap<String, Object>();
         jsonMap = mapper.readValue(jsonString, new TypeReference<Map<String, String>>(){}); // converts JSON to Map
         System.out.println(jsonMap);
      } catch(IOException ie) {
         ie.printStackTrace();
      }
   }
}

Output

{Name=Raja, Technology=Java}


Map to JSON

Syntax

public String writeValueAsString(Object value) throws JsonProcessingException

Example

import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ConvertMapToJSONTest {
   public static void main(String args[]) throws IOException {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = "";
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("Raja", "Java Technology");
      map.put("Ravi", "Python Technology");
      map.put("Adithya", "Spark Technology");
      map.put("Vamsi", "Web Technology");
      jsonString = mapper.writeValueAsString(map); // converts Map to JSON
      System.out.println(map);
   }
}

Output

{"Raja":"Java Technology", "Vamsi":"Web Technology", "Ravi":"Python Technology", "Adithya":"Spark Technology"}
raja
Published on 23-Sep-2019 14:46:58
Advertisements