How to convert a List to JSON array using the Jackson library in Java?


The ObjectMapper class is the most important class in the Jackson API that provides readValue() and writeValue() methods to transform JSON to Java Object and Java Object to JSON. We can convert a List to JSON array using the writeValueAsString() method of ObjectMapper class and this method can be used to serialize any Java value as a String.

Syntax

public String writeValueAsString(Object value) throws JsonProcessingException

Example

import java.util.*;
import com.fasterxml.jackson.databind.*;
public class ListToJSONArrayTest {
   public static void main(String args[]) {
      List<String> list = new ArrayList<>();
      list.add("JAVA");
      list.add("PYTHON");
      list.add("SCALA");
      list.add(".NET");
      list.add("TESTING");
      ObjectMapper objectMapper = new ObjectMapper();
      try {
         String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
         System.out.println(json);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Output

[ "JAVA", "PYTHON", "SCALA", ".NET", "TESTING" ]

Updated on: 06-Jul-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements