[英]How to read multiple JSON files and write it to a single JSON file using java
[英]How to read multiple JSON docs in single JSON file using Java?
我是JSON的新手,我想使用設備ID讀取JSON文檔,我在單個文件上有很多文檔,就像數據庫一樣:
{
"deviceType":"AccessPoint",
"transactionType":"response",
"messageType":"set_config",
"classes":[
{
"deviceType":"AccessPoint",
"classId":1,
"ipv4":"192.168.100.100",
"netmask":"192.168.100.100",
"ipv6":"192.168.100.100",
"className":"Interface",
"interfaceName":"wlan0",
"state":"UP",
"type":"wireless",
"deviceId":"1234",
"status":"waiting"
}
],
"deviceId":"1234",
"transactionId":"201675"
}
有時,類數組包含多個數組,例如索引[{},{},..]。 因此,如何在Java Web應用程序中使用搜索條件閱讀文檔。
出於好奇,對Jackson進行了一些操作(流分析器,因為提到了大量元素)。 我只是將其輸出為name:value,因此可以在邏輯上進行增強以適合您的口味。 這甚至還沒有接近生產,但這是一個好的開始。
import java.io.FileInputStream;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class TestClass {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("yourpath/transactions.json")) {
JsonFactory jf = new JsonFactory();
JsonParser jp = jf.createParser(fis);
//System.out.println(JsonToken.START_ARRAY);
// jp.setCodec(new ObjectMapper());
jp.nextToken();
while (jp.hasCurrentToken()) {
if (jp.getCurrentToken().equals(JsonToken.START_OBJECT)
|| jp.getCurrentToken().equals(JsonToken.START_ARRAY)
|| jp.getCurrentToken().equals(JsonToken.END_ARRAY)
|| jp.getCurrentToken().equals(JsonToken.END_OBJECT)) {
} else {
System.out.print(jp.getText());
jp.nextToken();
System.out.print(":");
System.out.print(jp.getText());
System.out.println();
}
jp.nextToken();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.