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 对象,或者反过来
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值