Java读取项目json文件并转为JSON对象

java哥 阅读:932 2021-04-01 11:29:10 评论:0

1、创建json文件(demo.json)

{
   
     
	"button": [ 
		{
   
     
			"type": "click", 
			"name": "今日歌曲", 
			"key": "V1001_TODAY_MUSIC" 
		}, 
		{
   
     
			"name": "菜单", 
			"sub_button": [ 
				{
   
     
					"type": "view", 
					"name": "搜索", 
					"url": "http://www.soso.com/" 
				}, 
				{
   
     
					"type": "miniprogram", 
					"name": "wxa", 
					"url": "http://mp.weixin.qq.com", 
					"appid": "wx286b93c14bbf93aa", 
					"pagepath": "pages/lunar/index" 
				}, 
				{
   
     
					"type": "click", 
					"name": "赞一下我们", 
					"key": "V1001_GOOD" 
				} 
			] 
		} 
	] 
} 

在这里插入图片描述
2、在pom.xml中添加依赖包

		<dependency> 
			<groupId>com.alibaba</groupId> 
			<artifactId>fastjson</artifactId> 
			<version>1.2.54</version> 
		</dependency> 
		<dependency> 
			<groupId>org.apache.commons</groupId> 
			<artifactId>commons-io</artifactId> 
			<version>1.3.2</version> 
		</dependency> 

3、创建测试类(FileDemo3.java)

package com.jeff.demo; 
 
import java.io.InputStream; 
 
import org.apache.commons.io.IOUtils; 
 
import com.alibaba.fastjson.JSONObject; 
 
public class FileDemo3 {
   
     
 
	public static JSONObject fileToJson(String fileName) {
   
     
		JSONObject json = null; 
		try ( 
			InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); 
		) {
   
     
			json = JSONObject.parseObject(IOUtils.toString(is, "utf-8")); 
		} catch (Exception e) {
   
     
			System.out.println(fileName + "文件读取异常" + e); 
		} 
		return json; 
	} 
 
	public static void main(String[] args) {
   
     
		String fileName = "doc/demo.json"; 
		JSONObject json = FileDemo3.fileToJson(fileName); 
		System.out.println(json); 
	} 
 
} 
 

4、控制台输出结果
在这里插入图片描述

标签:json
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号