In this post, we will see how to convert JSON array to Java List 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 List Object
We can use the ObjectMapper.readValue() method for converting a JSON text to collection object.
The following example demonstrates how to convert the JSON text to a List.
JacksonJsonToList.java
package net.javaguides.jackson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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 JacksonJsonToList {
@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\" ]";
List < String > progLangs = new ArrayList < > ();
progLangs = mapper.readValue(json, List.class);
for (Iterator < String > iterator = progLangs.iterator(); iterator.hasNext();) {
String progLang = (String) iterator.next();
System.out.println(progLang);
}
}
}
Output:
C
C++
Java
Java EE
Python
Scala
JavaScript
Jackson
Java
JSON
Comments
Post a Comment