Java读取项目json文件并转为JSON对象的操作
程序员文章站
2022-07-06 14:47:38
java读取项目json文件并转为json对象1、创建json文件(demo.json){ "button": [ { "type": "click", "name": "今日歌曲",...
java读取项目json文件并转为json对象
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、控制台输出结果
java读取json文件进行解析,string转json对象
string jsonfilepath = "c:/a.json"; file file = new file(jsonfilepath ); string input = fileutils.readfiletostring(file,"utf-8"); jsonobject obj = new jsonobject(input);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
上一篇: 浅谈super-vuex使用体验