用java如何实现实体列表和json之间的互转换
时间: 2024-03-10 19:49:19 浏览: 58
使用Java实现实体列表和JSON之间的互转换可以使用Jackson或Gson库。这里提供使用Jackson库的示例代码。
首先,需要在Maven或Gradle中添加Jackson库的依赖项。例如,在Maven中,可以将以下依赖项添加到pom.xml文件中:
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
```
然后,定义一个实体类Person:
```java
public class Person {
private String name;
private int age;
// getters and setters
}
```
接下来,将Person对象列表转换为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) throws JsonProcessingException {
List<Person> personList = new ArrayList<>();
personList.add(new Person("John", 30));
personList.add(new Person("Jane", 25));
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(personList);
System.out.println(json);
}
}
```
输出结果为:
```
[{"name":"John","age":30},{"name":"Jane","age":25}]
```
最后,将JSON格式转换回Person对象列表:
```java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
String json = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]";
ObjectMapper objectMapper = new ObjectMapper();
List<Person> personList = objectMapper.readValue(json, new TypeReference<List<Person>>() {});
System.out.println(personList);
}
}
```
输出结果为:
```
[Person{name='John', age=30}, Person{name='Jane', age=25}]
```
注意:在将实体类转换为JSON格式时,实体类必须有无参构造函数和getter/setter方法。在将JSON格式转换回实体类时,必须确保JSON格式正确,否则可能会抛出异常。
阅读全文