jackson jsonlines 處理-讀取以及生成
阿新 • • 發佈:2021-09-03
jsonlines 在資料分析處理以及批量json 處理中是比較常用的,以下是基於jackson 的處理
場景說明
基於jackson 讀取以及生成jsonlines
參考程式碼
jsonlines 格式
{"0":"ddd","1":"11","2":"111","3":"111"}
{"0":"ddd","1":"12","2":"112","3":"112"}
{"0":"ddd","1":"13","2":"113","3":"113"}
- 讀取
public static void readJsonLines() throws IOException {
InputStream stream = Application.class.getClassLoader().getResourceAsStream("demoapp22.ldjson");
JsonMapper reader= JsonMapper.builder().build();
MappingIterator<JsonNode> items = reader.readerFor(JsonNode.class).readValues(stream);
while (items.hasNextValue()){
System.out.println(items.nextValue());
}
}
- 生成
public static void writeExcelContent2JSONLines2(List<Object> input) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
try (OutputStream fileOutputStream = new FileOutputStream("demoapp22.ldjson")) {
try (SequenceWriter seq = objectMapper.writer()
// withRootValueSeparator 此處是核心,需要符合jsonlines的格式,資料就是一個pojo
.withRootValueSeparator("\n").writeValues(fileOutputStream)) {
input.forEach(new Consumer<Object>() {
@SneakyThrows
@Override
public void accept(Object s) {
seq.write(s);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
說明
以上基於jackson 進行jsonlines 的讀取以及寫入操作,對於需要整合jsonlines 的可以參考