【发布时间】:2023-01-31 01:58:49
【问题描述】:
我有一个 Java 方法,它使用流方法以 JSON 格式创建客户信息,并在使用 SmallRye Mutiny 的 Multi 以异步方法创建时返回。
我想将包装器添加到使用 Jackson JsonGenerator 创建的这个 JSON。我不明白如何添加相同的内容。我相信我需要利用Multi.createBy().concatenating()来实现this。
以下是我的方法:
public static Multi<Customer> generateCustomer(final Input input) {
try {
return Multi.createFrom().publisher(new CustomerPublisher(input));
} catch (Exception e) {
throw new NewException("Exception occurred during the generation of Customer : " + e);
}
}
上面的方法目前异步返回类似这样的东西:
[
{
"name":"Batman",
"age":45,
"city":"gotham"
},
{
"name":"superman",
"age":50,
"city":"moon"
}
]
我想向这个 JSON 添加一个包装器并创建如下内容:
{
"isA": "customerDocument",
"createdOn": "2022-10-10T12:29:43",
"customerBody": {
"customerList": [
{
"name": "Batman",
"age": 45,
"city": "gotham"
},
{
"name": "superman",
"age": 50,
"city": "moon"
}
]
}
}
所以我添加了一个执行此操作的方法,我想调用相同的方法,但我无法将相同的方法附加到我的 return Multi.createFrom().publisher
public class CustomerGenerator {
private ByteArrayOutputStream jsonOutput;
private JsonGenerator jsonGenerator;
private CustomerGenerator() {
try {
jsonOutput = new ByteArrayOutputStream();
jsonGenerator = new JsonFactory().createGenerator(jsonOutput).useDefaultPrettyPrinter();
} catch (IOException ex) {
throw new TestDataGeneratorException("Exception occurred during the generation of customer document : " + ex);
}
}
public static Multi < Customer > generateCustomer(final Input input) {
CustomerGenerator customerGenerator = new CustomerGenerator();
customerGenerator.wrapperStart();
try {
return Multi.createFrom().publisher(new CustomerPublisher(input));
} catch (Exception e) {
throw new NewException("Exception occurred during the generation of Customer : " + e);
} finally {
System.out.println("ALL DONE");
customerGenerator.wrapperEnd();
}
}
public void wrapperStart() {
try {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("type", "customerDocument");
jsonGenerator.writeStringField("creationDate", Instant.now().toString());
jsonGenerator.writeFieldName("customerBody");
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("customerList");
} catch (IOException ex) {
throw new TestDataGeneratorException("Exception occurred during customer document wrapper creation : " + ex);
}
}
public void wrapperEnd() {
try {
jsonGenerator.writeEndObject(); // End body
jsonGenerator.writeEndObject(); // End whole json file
} catch (IOException ex) {
throw new TestDataGeneratorException("Exception occurred during customer document wrapper creation : " + ex);
} finally {
try {
jsonGenerator.close();
System.out.println("JSON DOCUMENT STRING : " + jsonOutput.toString());
} catch (Exception e) {
// do nothing
}
}
}
}
【问题讨论】:
-
我创建了一个
jsongenerator来为你的第一个 json 创建包装器(不使用 mutiny),这对你有帮助吗? -
@dariosicily 非常感谢您的回复,但我不完全理解您的回复。您的意思是您已经使用您想提供的
JsonGenerator创建了 JSON 吗?我已经在使用JsonGenerator创建包装器并使用问题提供相同的包装器。我需要做的就是将该 JSON 附加到异步返回响应的叛变中。我做不到。
标签: java jackson reactive-streams mutiny smallrye