Jackson - Convert Java Set Object to JSON Array

In this post, we will see how to convert Java Set object into JSON array using the Jackson library.

Dependencies

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.

Jackson - Convert Java Set Object to JSON Array

Let's demonstrates how to convert a Set object to JSON is 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" ]

References


Comments