SpringBoot - 讀取JSON文件


前言

記錄下SpringBoot讀取JSON文件的方式


具體實現

  • JsonUtil.java
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class JsonUtil {

    /**
     * 讀取JSON文件轉換為字符串
     * @param filePath
     * @return
     */
    public static String readJsonFile(String filePath) {
        String jsonStr = "";
        try {
            File jsonFile = new File(filePath);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

}

轉換例子

  • 借助fastjson
<!-- fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.48</version>
</dependency>
  • 對象形式讀取轉換
String jsonStr = JsonUtil.readJsonFile("src/main/resources/json/xxx.json");
JSONObject result = JSONObject.parseObject(jsonStr);
  • 數組形式讀取轉換
String jsonStr = JsonUtil.readJsonFile("src/main/resources/json/xxx.json");
JSONArray result = JSONObject.parseArray(jsonStr);

- End -
夢想是咸魚
關注一下吧


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM