In this quick article, I will show how to convert a Map to a JSON object using the Jackson library.
Check out complete Jackson tutorial at Java Jackson JSON Tutorial with Examples.
We are using Jackson library to convert Java Map to JSON array so let's add below Jackson dependency to your project's classpath or pom.xml.
Maven pom dependency
Let’s first add the following dependencies to the pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
This dependency will also transitively add the following libraries to the classpath:
- jackson-annotations-2.9.8.jar
- jackson-core-2.9.8.jar
- jackson-databind-2.9.8.jar
Always use the latest versions on the Maven central repository for Jackson databind.
Example - Convert Map to JSON Object
The following example shows how to convert Map to JSON object using the ObjectMapper.writeValueAsString() method.
JacksonMapToJson.java
package net.javaguides.jackson;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JacksonMapToJson {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Map < String, Integer > days = new HashMap < > ();
days.put("MON", Calendar.MONDAY);
days.put("TUE", Calendar.TUESDAY);
days.put("WED", Calendar.WEDNESDAY);
days.put("THU", Calendar.THURSDAY);
days.put("FRI", Calendar.FRIDAY);
days.put("SAT", Calendar.SATURDAY);
days.put("SUN", Calendar.SUNDAY);
String json = mapper.writeValueAsString(days);
System.out.println(json);
}
}
Output:
{
"THU" : 5,
"TUE" : 3,
"WED" : 4,
"SAT" : 7,
"FRI" : 6,
"MON" : 2,
"SUN" : 1
}
Comments
Post a Comment
Leave Comment