Java读取资源文件中的JSON数组转List
2022-05-11 本文已影响0人
光芒121


需求是将图1中的 json 文件解析成List<Model>格式
注意:JAVA下的json文件保存一般都是去除所有的空格的,就像图一中右侧的数据全都是一行紧密排布,在进行解析。
import org.springframework.core.io.ResourceLoader;
@Autowired
private final ResourceLoader resourceLoader;
private List<VoiceVO> readJsonList() throws IOException {
Resource resource = resourceLoader.getResource("classpath:assets/voice/voice.json");
InputStream inputStream = resource.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader br = null;
List<VoiceVO> voiceResult;
try {
String data;
br = new BufferedReader(isr);
while ((data = br.readLine()) == null) {
throw new BadRequestException("请检查resource下的voice.json文件");
}
voiceResult = FabsBeanUtils.converterList(data, new TypeReference<List<VoiceVO>>() {});
} finally {
if (null != br) {
br.close();
}
isr.close();
inputStream.close();
}
return voiceResult;
}
字符串转list工具类
class FabsBeanUtils {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* 字符串转list
*/
public static <T> T converterList(String str, TypeReference<T> typeReference) {
if (StringUtils.isEmpty(str) || typeReference == null) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? str : OBJECT_MAPPER.readValue(str, typeReference));
} catch (IOException e) {
return null;
}
}
}