{
"patterns": [
{
"name": "Date",
"pattern": "/(0?[1-9]|1[0-2])-((0?[1-9])|((1|2)[0-9])|30|31)/"
},
{
"name": "Time",
"pattern": "/(2[0123]|[01]?[0-9]):[0-5][0-9]:[0-5][0-9]/"
},
{
"name": "Port",
"pattern": "/^\\d{4,5}$/"
},
{
"name": "Ip",
"pattern": "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
}
]
}
要读取的json格式如上所示。
需要用的代码如下所示:
String filePath = "attern.json";
String jsonContent = "";
try {
// 读取 JSON 文件的内容
jsonContent = new String(Files.readAllBytes(Paths.get(filePath)));
// 打印 JSON 内容
System.out.println("JSON Content: " + jsonContent);
// 在这里你可以根据需要将 JSON 内容转换为对象、数组等进行存储和处理
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONObject.parseObject(jsonContent);
JSONArray patterns= jsonObject.getJSONArray("patterns");
System.out.println(patterns);
首先是通过java自带的Files.readAllBytes()读取文件内容生成byte[],并new新的String。
接着用阿里的JSONObject对象和JSONArray数组来解析读取到的json对象即可