日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java的json解析工具_json文件解析工具类(java)

發布時間:2024/9/19 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java的json解析工具_json文件解析工具类(java) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

附上java解析json文件內容的工具類

1.工具類

import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.core.io.ClassPathResource;

import java.io.*;

/**

* @ClassName CommonUtil

* @Description TODO

* @Author lifay

* @Date 2020/2/18 10:21

**/

public class CommonUtil {

private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);

/**

* 讀取json文件返回數據

* @throws IOException

*/

public static Object readJsonData(String filePath,Class clazz){

String jsonString = null;

Reader reader = null;

try{

ClassPathResource resource = new ClassPathResource(filePath);

if (!resource.exists()) {

logger.warn("{}文件不存在!",filePath);

return null;

}

File file = resource.getFile();

reader = new InputStreamReader(new FileInputStream(file),"utf-8");

int ch = 0;

StringBuffer sb = new StringBuffer();

while ((ch = reader.read()) != -1) {

sb.append((char) ch);

}

reader.close();

jsonString = sb.toString();

} catch (IOException e){

logger.warn("{}文件內容解析失敗!",filePath);

return null;

}

return JSONObject.parseObject(jsonString,clazz);

}

}

2.調用

List users = (List) CommonUtil.readJsonData("/json/user.json", List.class);

3.json文件(json文件放在resources目錄下,結構為/src/main/resources/json/user.json)

[{"id":"1","name":"user1","age":"18"},{"id":"2","name":"user2","age":"28"}]

總結

以上是生活随笔為你收集整理的java的json解析工具_json文件解析工具类(java)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。