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.
public String writeValueAsString(Object value) throws JsonProcessingException
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(); } } }
[ "JAVA", "PYTHON", "SCALA", ".NET", "TESTING" ]
The above is the detailed content of How to convert List to JSON array using Jackson library in Java?. For more information, please follow other related articles on the PHP Chinese website!