欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解析(读取)JSON串(文件)

程序员文章站 2022-07-05 18:32:24
...

解析(读取)JSON串(文件)

1、JSON文件存放位置

解析(读取)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