Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-09-20 11:17:18
forward
1308 people have browsed it

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
Copy after login

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();
      }
   }
}
Copy after login

输出

[ "JAVA", "PYTHON", "SCALA", ".NET", "TESTING" ]
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template