Java中,list<实体类>转String
时间: 2024-03-21 16:17:19 浏览: 58
你可以使用Jackson库将List<实体类>转换为JSON字符串,示例代码如下:
```java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
List<Entity> entityList = List.of(
new Entity("A", 1),
new Entity("B", 2),
new Entity("C", 3)
);
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(entityList);
System.out.println(jsonString);
}
private static class Entity {
private String name;
private int value;
public Entity(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
}
```
输出结果为:
```json
[{"name":"A","value":1},{"name":"B","value":2},{"name":"C","value":3}]
```
阅读全文