我有一个Java方法,它以InputStream的形式获取JSON格式的客户信息列表。我想将 Package 器添加到这个JSON中,它是使用Jackson JsonGenerator
创建的。当我尝试将customerList
添加为树时,得到错误java.lang.IllegalStateException: No ObjectCodec defined
下面是通过我的方法获得的客户列表:
[
{
"name":"Batman",
"age":45,
"city":"gotham"
},
{
"name":"superman",
"age":50,
"city":"moon"
}
]
我想添加一个 Package ,并使它像这样:
{
"isA": "customerDocument",
"createdOn": "2022-10-10T12:29:43",
"customerBody": {
"customerList": [
{
"name": "Batman",
"age": 45,
"city": "gotham"
},
{
"name": "superman",
"age": 50,
"city": "moon"
}
]
}
}
以下是我的方法:
private InputStream generateJsonDocumentWrapper(final InputStream inputEventList) throws IOException {
final PipedInputStream jsonDocumentWriter = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(jsonDocumentWriter);
final ExecutorService executorService = Executors.newWorkStealingPool();
final JsonParser jsonParser = new JsonFactory().createParser(inputEventList);
final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
jsonParser.setCodec(objectMapper);
final JsonNode node = jsonParser.readValueAsTree();
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
executorService.execute( () -> {
try{
try (JsonGenerator jsonGenerator = jsonfactory.createGenerator(out)) {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("type", "customerDocument");
jsonGenerator.writeStringField("creationDate", Instant.now().toString());
jsonGenerator.writeFieldName("customerBody");
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("customerList")
jsonGenerator.writeRaw(":")
jsonGenerator.writeTree(node); // works fine with jsonGenerator.writeRawValue(IOUtils.toString(inputEventList, StandardCharsets.UTF_8));
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
jsonGenerator.flush();
} catch (IOException ex) {
throw new IOException();
}
}catch (Exception ex) {
ex.printStackTrace();
}
});
System.out.println("Wrpper DOCUMENT : " + IOUtils.toString(jsonDocumentWriter, StandardCharsets.UTF_8));
return jsonDocumentWriter;
}
如果我将InputStream
直接转换为String
,则它工作正常,但我不想使用IOUtils.toString(inputEventList, StandardCharsets.UTF_8)
,因此我尝试读取为树,但这会导致以下错误:
java.lang.IllegalStateException: No ObjectCodec defined
at com.fasterxml.jackson.core.base.GeneratorBase.writeTree(GeneratorBase.java:403)
at my.package.CustomerWrapperGenerator.lambda$generateJsonDocumentWrapper$4(CustomerWrapperGenerator.java:319)
at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1395)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:373)
1条答案
按热度按时间yh2wf1be1#
我能够使它的工作如下: