json 文件打读取
生活随笔
收集整理的這篇文章主要介紹了
json 文件打读取
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1。獲取文件路徑
/** BookController.class.getClassLoader().getResource("static/json/book_nav.json").getPath() 獲取當(dāng)期運行時的項目json文件路徑*/JSONObject json = JsonResourceUtils.getJsonObjFromResource(BookController.class.getClassLoader().getResource("static/json/book_nav.json").getPath());Set<Entry<String, Object>> entrySets=json.entrySet();/** 取出json數(shù)據(jù)*/for(Entry<String, Object> entrySet: entrySets){if(entrySet.getKey().equals("bookNavs"))model.addAttribute("bookNavs",entrySet.getValue());}2.讀取json文件
package com.feilong.reptile.util;import java.io.File; import java.io.IOException;import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger;import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject;public class JsonResourceUtils{private static Logger logger = Logger.getLogger(JsonResourceUtils.class);/** filePath文件路徑* @param filePath*/public static JSONObject getJsonObjFromResource(String filePath){JSONObject json = null;if (!filePath.contains(".json")) {filePath += ".json";}File file = new File(filePath);if (file.exists()) {String content=null;try {content = FileUtils.readFileToString(file, "UTF-8");} catch (IOException e) { e.printStackTrace();logger.info("readFileToString: " + e.getMessage());}json = JSON.parseObject(content);} else {logger.info("file not exist!");}return json;}}?3.pom 依賴
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.58</version></dependency><!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version> </dependency>?
轉(zhuǎn)載于:https://www.cnblogs.com/jiangfeilong/p/11108316.html
總結(jié)
以上是生活随笔為你收集整理的json 文件打读取的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到打鬼怪代表什么预兆
- 下一篇: 做梦梦到辣子是什么意思