美文网首页
Java读取资源文件中的JSON数组转List

Java读取资源文件中的JSON数组转List

作者: 光芒121 | 来源:发表于2022-05-11 15:21 被阅读0次
1、存放在resource下的json 2、数据格式

需求是将图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;
        }
    }
}

相关文章

网友评论

      本文标题:Java读取资源文件中的JSON数组转List

      本文链接:https://www.haomeiwen.com/subject/wxwdurtx.html