Convert Java Map Collection Object to JSON String using Jackson


⌛️ 4 minute read! Difficulty: Medium

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!

Top Hashtags:

Advertisements

Advertisements




Advertisements