JSON字符串数据转换指定实体对象数据
一、引入需要的maven依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.69</version> </dependency>
二、创建实体类对象
import com.songwp.config.ExcelField; import lombok.*; import java.io.Serializable; /** * @Description * @Author songwp * @Date 2023/2/2 9:08 * @Version 1.0.0 **/ @Data @Builder @AllArgsConstructor @NoArgsConstructor public class UserEntity implements Serializable { @ExcelField("序号") private Integer id; @ExcelField("姓名") private String name; @ExcelField("性别") private Integer sex; }
三、具体方法测试代码块
// 1.将字符串类型的集合数据转成泛型为(对象-Object)类型的集合 String dataList = "[{\"id\":1,\"name\":\"张三丰\",\"sex\":0},{\"id\":2,\"name\":\"张三丰\",\"sex\":0},{\"id\":3,\"name\":\"张三\",\"sex\":0},{\"id\":4,\"name\":\"李四\",\"sex\":0},{\"id\":5,\"name\":\"张三丰\",\"sex\":1}]"; List<UserEntity> userEntities = JSON.parseArray(dataList, UserEntity.class); System.out.println(userEntities); // 2.将字符串类型的数据转成(对象-Object) String data = "{\"id\":1,\"name\":\"张三丰\",\"sex\":0}"; UserEntity userEntity = JSON.parseObject(data,UserEntity.class); System.out.println(userEntity);
四、测试结果输出
[UserEntity(id=1, name=张三丰, sex=0), UserEntity(id=2, name=张三丰, sex=0), UserEntity(id=3, name=张三, sex=0), UserEntity(id=4, name=李四, sex=0), UserEntity(id=5, name=张三丰, sex=1)]
UserEntity(id=1, name=张三丰, sex=0)
古今成大事者,不唯有超世之才,必有坚韧不拔之志!