首页 > 其他分享 >SpringBoot中读取JSON文件信息并转换为Map对象

SpringBoot中读取JSON文件信息并转换为Map对象

时间:2023-01-29 10:01:21浏览次数:46  
标签:Map java HashMap reader JSON new import SpringBoot

SpringBoot中读取JSON文件信息并转换为Map对象

需要引入的依赖

<dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.23</version>
</dependency>

实现代码

package com.cell.system.utils;

import com.alibaba.fastjson2.JSONObject;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

public class ReadPredictJson {
    public static HashMap parseJson(String path) throws IOException {
        BufferedReader reader;
        StringBuilder str = new StringBuilder();
        FileInputStream fileInputStream = new FileInputStream(path);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8);
        reader = new BufferedReader(inputStreamReader);
        // 读取文件信息
        String tempString;
        while ((tempString = reader.readLine()) != null) {
            str.append(tempString);
        }
        reader.close();
        // 转换为HashMap对象
        return JSONObject.parseObject(str.toString(), HashMap.class);
//        return (HashMap<String, Object>) JSON.parse(str.toString());
    }


    public static void main(String[] args) throws IOException {
        HashMap result = ReadPredictJson.parseJson("C:/Users/reion/Desktop/Agaricus_perobscurus(fs-02).json");
        System.out.println(result);
    }
}

输出结果

{Predict=deviation, imgPath=C:\Users\reion\Desktop\Agaricus_perobscurus(fs-02).jpg, Predict Possibility={"adenoid":2.7501989734446397E-6,"allergic":0.20632338523864746,"chronic":0.09952230006456375,"deviation":0.6917710304260254,"nasophary":8.482194147063638E-8,"nomal":0.002183763077482581,"rhinosinusitis":0.00019669618632178754}, imgCamPath=C:\Users\reion\Desktop\Agaricus_perobscurus(fs-02)_Cam.jpg}

标签:Map,java,HashMap,reader,JSON,new,import,SpringBoot
From: https://www.cnblogs.com/Reion/p/17071833.html

相关文章