應用場景
- Jar 包或 War 包引用一個外部文件作爲項目運行的配置文件
- Json 採用 key - value 格式,作爲配置文件,是一個很好的選擇
- JSON 是一種文本形式的數據交換格式,它比XML更輕量、比二進制容易閱讀和編寫,調式也更加方便
- 讀取文件相對讀取數據庫,效率更高
待讀取的外部 JSON 文件
{
"name": "鍾力",
"skill": {
"JavaScript": {
"level": "9",
"class": ["JQuery", "Vue", "AngularJS", "React"]
},
"NodeJS": {
"level": "8",
"class": ["Express"]
},
"Java": {
"level": "7",
"class": ["Spring", "SpringBoot", "SpringCloud"]
},
"SQL": {
"level": "7",
"class": ["MySQL", "MongoDB", "Redis"]
}
}
}
Java 代碼
package com.swmfizl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import com.google.gson.Gson;
public class ReadJsonFile {
public static Map<String, Object> readJsonFile(String fileName) {
Gson gson = new Gson();
String json = "";
try {
File file = new File(fileName);
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
int ch = 0;
StringBuffer buffer = new StringBuffer();
while ((ch = reader.read()) != -1) {
buffer.append((char) ch);
}
reader.close();
json = buffer.toString();
return gson.fromJson(json, Map.class);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
System.out.println(readJsonFile("C:\\Users\\ZhongLi\\Desktop\\config.json"));
}
}
讀取結果
{name=鍾力, skill={JavaScript={level=9, class=[JQuery, Vue, AngularJS, React]}, NodeJS={level=8, class=[Express]}, Java={level=7, class=[Spring, SpringBoot, SpringCloud]}, SQL={level=7, class=[MySQL, MongoDB, Redis]}}}
Gson
- Gson 是用來在 Java 對象和 JSON 數據之間進行映射的 Java 類庫
- 可以將一個 JSON 字符串轉成一個 Java 對象,或者反過來