PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

如何使用Java中的Jackson库将List转换为JSON数组?

WBOY
WBOY 转载
2023-09-20 11:17:18 900浏览

如何使用Java中的Jackson库将List转换为JSON数组?

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

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" ]

以上就是如何使用Java中的Jackson库将List转换为JSON数组?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除