json文件中存放jsonArray,将其读取出来并转换为java对象,转换的对象需要根据传入的对象动态转换,工具类编写如下:
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @create 2023/9/15 15:32
* @description
*/
@Slf4j
public class JsonToolUtil {
public static <T> List<T> readJsonArray(String fileName, Class<T> clazz) throws IOException {
Path f = Paths.get(fileName);
// 判断文件是否存在
if (!Files.exists(f)) {
log.error(String.format("file[%s] not exists", fileName));
return Collections.emptyList();
}
List<String> fileList = Files.readAllLines(f);
// 判断文件是否是空文件
if (fileList.isEmpty()) {
log.warn(String.format("file[%s] is empty", fileName));
return Collections.emptyList();
}
// 将读取的json文件数据转换为对应的bean
List<T> list = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
for(String it : fileList){
list.add(mapper.readValue(it, clazz));
}
return list;
}
}
需要转换的java对象:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @create 2023/9/15 15:44
* @description
*/
@Data
@EqualsAndHashCode(callSuper = false)
// 并不包含所有的json属性
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserDto {
// JsonProperty可以将对应的jsonkey指定变量
@JsonProperty("Name")
private String name;
@JsonProperty("Gender")
private String gender;
@JsonProperty("Age")
private Integer age;
}
测试:
import com.littledyf.domain.UserDto;
import java.io.IOException;
import java.util.List;
/**
* @create 2023/9/15 15:46
* @description
*/
public class JsonMain {
public static void main(String[] args) throws IOException {
List<UserDto> userDtoList = JsonToolUtil.readJsonArray("C:\\Users\\dengyifan\\Desktop\\test.json", UserDto.class);
System.out.println(userDtoList);
}
}
测试结果: