java的list转json
时间: 2023-12-19 12:30:08 浏览: 99
使用Jackson库是将Java的List转换为JSON格式的最简单方法。以下是一个示例代码,演示如何使用Jackson库将List<String>转换为JSON字符串:
```java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
public class ListToJsonExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
ObjectMapper objectMapper = new ObjectMapper();
try {
String json = objectMapper.writeValueAsString(list);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
```
输出结果为:
```
["apple","banana","orange"]
```
阅读全文