Java 读取 JSON 文件转成 Map 对象

应用场景

  • Jar 包或 War 包引用一个外部文件作为项目运行的配置文件
  • Json 采用 key - value 格式,作为配置文件,是一个很好的选择
  • JSON 是一种文本形式的数据交换格式,它比XML更轻量、比二进制容易阅读和编写,调式也更加方便
  • 读取文件相对读取数据库,效率更高

待读取的外部 JSON 文件

  • 内容随意,但必选按 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 代码

/**
 * @author ZhongLi
 */
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) {
		// TODO 自动生成的方法存根
		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 对象,或者反过来
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章