通过使用spring引导插入来自循环的所有数据来创建JSON数组



我已经实现了一个从.pcap文件导入数据的代码。它工作正常。它读取cap文件,并在控制台中显示结果。

代码是

@SpringBootApplication
public class SpringBootSecurityJwtMongodbApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityJwtMongodbApplication.class, args);
}

@Bean
public ApplicationRunner runner(FTPConfiguration.GateFile gateFile) {
return args -> {
List<File> files = gateFile.mget(".");
for (File file : files) {
System.out.println("Result:" + file.getAbsolutePath());
run(file);
}
};
}
void run(File file) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Pcap pcap = Pcap.openStream(file);
pcap.loop(
packet -> {
if (packet.hasProtocol(Protocol.TCP)) {
TCPPacket packet1 = (TCPPacket) packet.getPacket(Protocol.TCP);
String Time = formatter.format(new Date(packet1.getArrivalTime() / 1000));
String Source = packet1.getSourceIP();
String Destination = packet1.getDestinationIP();
String Protocol = packet1.getProtocol().toString();
Long Length = packet1.getTotalLength();
System.out.printf("%s | %s | %s | %s | %d n", Time, Source, Destination, Protocol, Length);
} else if (packet.hasProtocol(Protocol.UDP)) {
UDPPacket packet1 = (UDPPacket) packet.getPacket(Protocol.UDP);
String Time = formatter.format(new Date(packet1.getArrivalTime() / 1000));
String Source = packet1.getSourceIP();
String Destination = packet1.getDestinationIP();
String Protocol = packet1.getProtocol().toString();
Long Length = packet1.getTotalLength();
System.out.printf("%s | %s | %s | %s | %d n", Time, Source, Destination, Protocol, Length);
} else {
System.out.println("Not found protocol. | " + packet.getProtocol());
}
return packet.getNextPacket() != null;
}
);
}
}

我想把这些数据放到一个JSON数组中。因此输出应该如下所示。

[
{"Destination":"116.50.76.245","Length":119,"Time":"03:41:08","Protocol":"udp","Source":"4.2.2.2"},
{"Destination":"10.64.33.73","Length":92,"Time":"03:41:06","Protocol":"tcp","Source":"91.198.174.192"},
{"Destination":"4.2.2.2","Length":74,"Time":"03:41:08","Protocol":"udp","Source":"10.64.43.166"},
{"Destination":"4.2.2.2","Length":74,"Time":"03:41:08","Protocol":"udp","Source":"10.64.43.166"}
]

有人能帮我做这个吗?

只需创建一个JSONArray的实例并将其传递给run方法,然后在packet -> {}方法体内创建JSONObject的实例,并将JSONObject填充并推送给传递的JSONArray实例。以下是最小代码:

@Bean
public ApplicationRunner runner(FTPConfiguration.GateFile gateFile) {
...
JSONArray arr = new JSONArray();
for (File file : files) {
System.out.println("Result:" + file.getAbsolutePath());
run(file, arr);
}
...
}
void run(File file, JSONArray arr) throws IOException {
...
packet -> {
...
if (packet.hasProtocol(Protocol.TCP)) {
...
JSONOBject obj = new JSONOBject();
obj.put("Desitnation", destination);
// set other properties
arr.add(obj);
...
}
// same for else if block
...
}
...
}

最新更新