如何使用 Kotlin 将列表从 json 映射/转换为重复的 proto 字段

问题描述

上下文:我创建了一个暴露 gRPC 端点的微服务。它调用一个包含列表的 Rest Service,并且必须按照原型设计进行响应。

我可以通过 forEach 轻松访问它:

certainList.forEach{
    grpcResponSEObject.addRepeatedprotofield(
        protofield.newBuilder()
        .setField1(it.field1)
        .setField2(it.field2)
        .build()
    )
}

出于学习目的,我希望使用 map 或 mapTo 和 kotlin lambda 达到相同的结果。

其余服务响应 get 请求:

[
    {
        "certain_list": [
          {
            "field1": 1,"field2": a
          },{
            "field1": 2,"field2": b
          }
        ],"id": "1234"
    }
]

我使用一个非常简单的 http 客户端来使用这样的休息服务

import io.micronaut.http.annotation.Get
import io.micronaut.http.client.annotation.Client


@Client("http://localhost:3000/certains_rest_service")
interface HttpClient {
    @Get("/{?id}")
    fun get(id: String?): MyParentModel?

}

MyParentModel.kt

data class MyParentModel (
        var id: String,var certainList: List<MyChildModel>

)

MyChildModel.kt

data class MyChildModel(
        var field1: Int,var field2: String
)

现在是 gRPC/Proto 代码

Syntax = "proto3";

option java_multiple_files = true;

package ...

import "google/api/annotations.proto";

service MyService {

  rpc Get (GetMyRequest) returns (MyResponse) {
  }
}

message GetMyRequest{
    string id = 1;
}

message MyResponse {
  string id = 1;
  repeated MyRepeatedobject mylist = 2;
}

message MyRepeatedobject{
    int32 field1 = 1;
    string field2 = 2;
}

gRPC 端点实现(仅相关部分)

我用

达到了想要的结果
certainList.forEach{
    grpcResponSEObject.addRepeatedprotofield(
        protofield.newBuilder()
        .setField1(it.field1)
        .setField2(it.field2)
        .build()
    )
}

但我更喜欢(虚构的解决方案)之类的东西

certainList.map(t,grpcResponSEObject.addRepeatedprotofield(t.field1,t.field2))

基本上,当我们将 proto 文件与 io.grpc:protoc-gen-grpc-kotlin 一起使用时,它会自动生成要实现的端点接口及其存根。从 restservice 我收到一个列表,我需要填写由重复 proto 字段产生的响应对象。一种可能的帮助是,如果您指出一些示例,其中 gRPC 端点从休息服务获取列表并将其作为 gRPC 中的响应进行应答。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)