Home >Java >javaTutorial >How to convert List to JSON array using Jackson library in Java?

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

WBOY
WBOYforward
2023-09-20 11:17:181319browse

How to convert List to JSON array using 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();
      }
   }
}

输出

[ "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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete