In this quick article, I will show how to convert a Set to JSON array using Jackson.
Check out complete Jackson tutorial at Java Jackson JSON Tutorial with Examples.
We are using Jackson library to convert Java Set to JSON array so let's add below Jackson dependency to your project's 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 Set to JSON array using Jackson
The following example shows how to convert a Set object to JSON array using the ObjectMapper.writeValueAsString() method.
JacksonSetToJson.java
package net.javaguides.jackson;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JacksonSetToJson {
public static void main(String[] args) throws JsonProcessingException {
// Create ObjectMapper object.
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Set < String > progLangs = new HashSet < > ();
progLangs.add("C");
progLangs.add("C++");
progLangs.add("Java");
progLangs.add("Java EE");
progLangs.add("Python");
progLangs.add("Scala");
progLangs.add("JavaScript");
// Serialize Object to JSON.
String json = mapper.writeValueAsString(progLangs);
// Print json
System.out.println(json);
}
}
Output:
[ "Java EE", "Java", "C++", "C", "Scala", "JavaScript", "Python" ]
Comments
Post a Comment
Leave Comment