java8以上,从JSONArray转成实体类A,再从实体类A转成另一个实体类B
时间: 2024-03-02 21:49:29 浏览: 59
可以使用Jackson库来实现JSONArray转成实体类A,以及实体类A转成实体类B。
1. JSONArray转成实体类A
假设JSONArray的格式如下:
```
[{"name":"张三","age":20},{"name":"李四","age":25}]
```
可以定义实体类A如下:
```java
public class Person {
private String name;
private int age;
// 省略getter和setter方法
}
```
使用Jackson的ObjectMapper类可以将JSONArray转成实体类A的List:
```java
ObjectMapper mapper = new ObjectMapper();
List<Person> personList = mapper.readValue(jsonArray.toString(), new TypeReference<List<Person>>() {});
```
2. 实体类A转成实体类B
假设实体类A和实体类B的定义如下:
```java
public class Person {
private String name;
private int age;
// 省略getter和setter方法
}
public class Employee {
private String name;
private int age;
private String department;
// 省略getter和setter方法
}
```
可以使用ObjectMapper的convertValue方法将实体类A转成实体类B:
```java
Person person = new Person();
person.setName("张三");
person.setAge(20);
ObjectMapper mapper = new ObjectMapper();
Employee employee = mapper.convertValue(person, Employee.class);
employee.setDepartment("技术部");
```
阅读全文