Convert Java Map Collection Object to JSON String using Jackson


Post Banner

Step 1: Make sure to add Jackson dependency in your Java Gradle/Maven Project

Gradle:
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.4'
Maven:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.4</version>
</dependency>

Step 3: Java Collection Map to JSON String

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JavaMapToJsonString {

    public static void main(String[] args) {
        try {

            Map<String,String> employeeMap1 = new HashMap<>();
            employeeMap1.put("empName","Mike");
            employeeMap1.put("empAge","34");
            employeeMap1.put("empDept","Finance");

            Map<String,String> employeeMap2 = new HashMap<>();
            employeeMap2.put("empName","Harry");
            employeeMap2.put("empAge","33");
            employeeMap2.put("empDept","Insurance");

            ObjectMapper objectMapper = new ObjectMapper();
            String empJson1 = objectMapper.writeValueAsString(employeeMap1);
            String empJson2 = objectMapper.writeValueAsString(employeeMap2);
            System.out.println(empJson1);
            System.out.println(empJson2);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Output:

{"empName":"Mike","empAge":"34","empDept":"Finance"}
{"empName":"Harry","empAge":"33","empDept":"Insurance"}



Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.