我有一个Java方法,它使用流方法创建JSON格式的客户信息,并在使用SmallRye Mutiny
中的Multi
以异步方法创建时返回。
我想给这个JSON添加一个 Package 器,这个JSON是用Jackson JsonGenerator
创建的,我不知道怎么添加,我相信我需要用Multi.createBy().concatenating()
来实现这个。
下面是我的方法:
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添加一个 Package 器,并创建如下所示的内容:
{
"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
}
}
}
}
1条答案
按热度按时间u91tlkcl1#
您的方法无法实现,因为您 Package 了
CustomGenerator
控件之外的随机输入。由于只有当所有发出的
Customer
对象都发出时才能生成最终输出,并且假设您希望保留面向对象的方法(即不转换为发出JSON令牌),则应该收集发出的客户,然后将收集到的项 Package 到最终JSON输出中: