gpt4 book ai didi

java - 填充 proto 的重复元素

转载 作者:行者123 更新时间:2023-12-02 09:36:40 24 4
gpt4 key购买 nike

尝试生成部门数组,这是我的尝试。

原始文件

service DepartmentService {
rpc findAll(Request) returns (Response);
}

message Department {
int64 id = 1;
string name = 2;
}

message Request {
string id = 1;
}

message Response {
int32 code = 1;
repeated Department departments = 2;
}

对应的java代码。

public void findAll(DepartmentOuter.Request request, StreamObserver<DepartmentOuter.Response> responseObserver) {
MongoCursor<Document> cursor = database
.getCollection("department")
.find()
.iterator();

DepartmentOuter.Response.Builder builder = DepartmentOuter.Response.newBuilder();
while (cursor.hasNext()) {
Document document = cursor.next();

DepartmentOuter.Department department = DepartmentOuter.Department
.newBuilder()
.setId(Integer.parseInt(document.getString("_id")))
.setName(document.getString("name")).build();

builder.addDepartments(department);


}



responseObserver.onNext(DepartmentOuter.Response.newBuilder().setCode(0).setDepartments(builder).build());
}

我在这段代码的最后一行遇到了问题。如何将填充输出发送到客户端?

responseObserver.onNext(DepartmentOuter.Response.newBuilder().setCode(0).setDepartments(builder).build());

<小时/>

编辑 - 重命名后

原始文件

service DepartmentService {
rpc findAll(Request) returns (Response);
}

message Department {
int64 id = 1;
string name = 2;
}

message Request {
string id = 1;
}

message Response {
int32 code = 1;
repeated Department department = 2;
}

@Override
public void findAll(DepartmentOuter.Request request, StreamObserver<DepartmentOuter.Response> responseObserver) {
MongoCursor<Document> cursor = database
.getCollection("department")
.find()
.iterator();

DepartmentOuter.Response.Builder builder = DepartmentOuter.Response.newBuilder();
while (cursor.hasNext()) {
Document document = cursor.next();

DepartmentOuter.Department department = DepartmentOuter.Department
.newBuilder()
.setId(Integer.parseInt(document.getString("_id")))
.setName(document.getString("name")).build();

builder.addDepartment(department);
}

responseObserver.onNext(DepartmentOuter.Response.newBuilder().setCode(0).setDepartment.build());
}

enter image description here

最佳答案

responseObserver.onNext(DepartmentOuter.Response.newBuilder().setCode(0).setDepartments(builder).build());

departments 是一个重复字段,因此应该是 addDepartments 而不是 setDepartments。您可以调用 setDepartments(someIndex, someDepartment),但只有在您之前至少向构建器添加了 someIndex+1 值时才有效;你还没有,因为它是一个新的构建器。

但是builder无论如何都是一个DepartmentOuter.Response.Builder,而不是一个Department,所以这也不起作用。目前尚不清楚您打算做什么;也许:

responseObserver.onNext(builder.setCode(0).build());

关于java - 填充 proto 的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57451653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com