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)
posted @ 2023-04-13 11:08  [奋斗]  阅读(359)  评论(0编辑  收藏  举报