Java讀取專案json檔案並轉為JSON物件的操作
阿新 • • 發佈:2021-08-13
讀取專案on檔案並轉為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>common客棧s-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 jWGrvdcom.alibaba.fastjson.JSONObject; public class FileDemo3 { public static JSONObject fileToJson(String fileName) { JSONObject json = null; try ( InputStream is = Thread.currentThread().getContextClassLoaderjWGrvd().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);
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。