java如何将list<VO>中所有对象输出成json格式,并打印出来system.out,每个对象之间通过换行符隔开,用具体代码表示下
时间: 2024-03-15 21:46:45 浏览: 123
List<Object>转Json
5星 · 资源好评率100%
您可以使用Jackson库实现将List<VO>转换为JSON格式并打印出来。以下是示例代码:
```java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<VO> voList = new ArrayList<>();
voList.add(new VO("Tom", 20));
voList.add(new VO("Jerry", 18));
voList.add(new VO("Lucy", 22));
ObjectMapper mapper = new ObjectMapper();
for (VO vo : voList) {
try {
String json = mapper.writeValueAsString(vo);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
}
class VO {
private String name;
private int age;
public VO(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
输出结果为:
```
{"name":"Tom","age":20}
{"name":"Jerry","age":18}
{"name":"Lucy","age":22}
```
每个对象之间通过换行符隔开。
阅读全文