Convert Set to JSON Array Using Jackson

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:
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.

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();

        Set < String > progLangs = new HashSet < > ();
        progLangs.add("Java EE");
        // Serialize Object to JSON.
        String json = mapper.writeValueAsString(progLangs);

        // Print json


[ "Java EE", "Java", "C++", "C", "Scala", "JavaScript", "Python" ]

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course