解析(读取)JSON串(文件)
程序员文章站
2022-07-05 18:32:24
...
解析(读取)JSON串(文件)
1、JSON文件存放位置
2、JSON文件
{
"took": 25,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "test_index",
"_type": "_doc",
"_id": "WaM573IBve72Lwpkd7GZ",
"_score": 1,
"_source": {
"f1": "1111111111",
"f2": "109.130.21.56",
"f3": 368,
"sysCreateTime": 1593151201391
}
},
{
"_index": "test_index",
"_type": "_doc",
"_id": "BTR32REG32RVBG4353V3",
"_score": 1,
"_source": {
"f1": "2222222222",
"f2": "119.10.2.156",
"f3": 68,
"sysCreateTime": 1593151201391
}
},
{
"_index": "test_index",
"_type": "_doc",
"_id": "GTR12GREGQ23R43FR23V",
"_score": 1,
"_source": {
"f1": "3333333333",
"f2": "139.130.21.56",
"f3": 8,
"sysCreateTime": 1593151201391
}
}
]
}
}
3、Maven依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
</dependency>
4、代码
String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Test
void testJson(){
String path = Delete111ApplicationTests.class.getClassLoader().getResource("test.json").getPath();
String str = readJsonFile(path);
JSONObject jsonObject = JSON.parseObject(str);
JSONArray jsonArray = jsonObject.getJSONObject("hits").getJSONArray("hits");
for (int i = 0; i < jsonArray.size(); i++) {
System.out.println(jsonArray.getJSONObject(i).getJSONObject("_source").getString("f1"));
}
}
5、输出结果
1111111111
2222222222
3333333333
推荐阅读
-
python读取json文件并将数据插入到mongodb的方法
-
.net core 读取appsettings.json 文件中文乱码的问题
-
Python实现读取json文件到excel表
-
干货:.net core实现读取appsettings.json配置文件(建议收藏)
-
JAVA使用POI(XSSFWORKBOOK)读取EXCEL文件过程解析
-
Python解析并读取PDF文件内容的方法
-
ASP.NET Core自定义本地化教程之从文本文件读取本地化字符串
-
c# 自定义解析JSON字符串数据
-
2018-10-10 在浏览器插件中读取JSON资源文件
-
python解析json串与正则匹配对比方法