Serialization – How to convert Map to JSON string using Jackson API


This tutorial shows how to convert a Java map to JSON string using Jackson’s data binding. In the previous tutorials, I explained converting Java Objects/Arrays to JSON String using Jackson API. You can refer to the below tutorials.

Serialization – How to create JSON Payload from Java Object – Jackson API

How to create JSON Array Payload using POJO – Jackson API

How to create Nested JSON Object using POJO – Jackson API

To start off, add the latest Jackson dataformat Maven dependency to the project.


Sample JSON

  "skillset" : [ 
                 "Power BI" 
  "gender" : "female",
  "DOB" : "12-02-1985",
  "name" : "Vibha Singh",
  "contactNumber" : "+919999988822",
  "employeeId" : "10342256",
  "location" : "Dublin",
  "emailId" : "",
  "salary" : "75000.0"

First, we will populate a Map, then convert them into JSON and later write that JSON to a file.

	public void SerializationMapTest() {

		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> inputMap = new HashMap<String, Object>();

		inputMap.put("employeeId", "10342256");
		inputMap.put("name", "Vibha Singh");
		inputMap.put("DOB", "12-02-1985");
		inputMap.put("salary", "75000.0");
		inputMap.put("location", "Dublin");
		inputMap.put("contactNumber", "+919999988822");
		inputMap.put("emailId", "");
		inputMap.put("gender", "female");

		List<String> skillset = new ArrayList<String>();

		skillset.add("Power BI");

		inputMap.put("skillset", skillset);

		// Converting map to a JSON payload as string
		try {
			String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(inputMap);
		} catch (JsonProcessingException e) {

		String userDir = System.getProperty("user.dir");

        //Writing JSON on a file
		try {
					.writeValue(new File(userDir + "\\src\\test\\resources\\JSONFromMap.json"), inputMap);
		} catch (IOException e) {



As mentioned above, the new JSON is saved in a file and placed under src/test/resources.

Below is the file with JSON.

Congratulations, we are done. We have successfully created a JSON using HashMap.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s