In this quick article, I will show how to convert a List 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 List to JSON array so let's add below Jackson dependency to your project's classpath or 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 List to JSON Array Using Jackson
The following example shows how to convert List object to JSON array using the ObjectMapper.writeValueAsString() method.
JacksonListToJson.java
package net.javaguides.jackson;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Using Jackson API for list serialization and deserialization
* @author ramesh fadatare
*
*/
public class JacksonListToJson {
public static void main(String[] args) throws JsonProcessingException {
// Create ObjectMapper object.
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
List < String > progLangs = new ArrayList < > ();
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:
[ "C", "C++", "Java", "Java EE", "Python", "Scala", "JavaScript" ]
Comments
Post a Comment
Leave Comment