Jackson - Convert JSON Array to Java Set Object



In this post, we will see how to convert JSON array to Java Set object 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 JSON Array to Java Set Object

We can use the ObjectMapper.readValue() method for converting JSON text to Set object.
The following example demonstrates how to convert the JSON text to Set.

JacksonJsonToSet.java

package net.javaguides.jackson;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonJsonToSet {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

        // Create ObjectMapper object.
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        String json = "[ \"C\", \"C++\", \"Java\", \"Java EE\", \"Python\", \"Scala\", \"JavaScript\" ]";

        Set < String > progLangs = new HashSet < > ();
        progLangs = mapper.readValue(json, Set.class);

        for (Iterator < String > iterator = progLangs.iterator(); iterator.hasNext();) {
            String progLang = (String) iterator.next();
            System.out.println(progLang);
        }
    }
}
Output:
Java EE
Java
C++
C
Scala
JavaScript
Python

Comments