go - 如何将嵌套结构转换/转换为 Protobuf?

标签 go struct protocol-buffers proto

我正在开发一个个人项目,并且是第一次使用 Go。我使用结构来操作数据并将数据存储在文件中,我使用 proto 作为编码器。

在项目中,我的原型(prototype)定义如下所示:

message AssetPairInfo {
    string Altname = 1;
    string AssetClassBase = 2;
    string Base = 3;
    .... Additional fields
}

message AssetPairsResponse {
  AssetPairInfo ADACAD = 1;
  AssetPairInfo ADAETH = 2;
  AssetPairInfo ADAEUR = 3;
  ... Additional fields
}

我的结构如下所示:

type AssetPairInfo struct {
    Altname string `json:"altname"`
    AssetClassBase string `json:"aclass_base"`
    Base string `json:"base"`
    ... Additional fields
}

type AssetPairsResponse struct {
    ADACAD   AssetPairInfo
    ADAETH   AssetPairInfo
    ADAEUR   AssetPairInfo
    ... Additional fields
}

我只包含了每个结构体的 3 个定义,但我的结构体有超过 70 个定义。 我正在寻找一种编程方法来将 AssetPairsResponse 结构转换为我的 protobuf。鉴于我的 struct 和 protobuf 共享相同的字段(除了额外生成的 protobuf 字段),似乎应该可以做到。

有什么想法吗?

最佳答案

作为解决方法,如果模型(您的自定义和原型(prototype)消息)共享相同的 json 标记名称,您可以解码您的自定义结构,然后编码原型(prototype)消息。例如:

myModel := model.AssetPairsResponse{
....
}

b, err := json.Marshal(myModel)


myProto := &pb.AssetPairsResponse{}


json.Unmarshal(b, myProto)

关于go - 如何将嵌套结构转换/转换为 Protobuf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65407336/

相关文章:

c# - 作为通用结构的强类型 Guid

c++ - 如何通过管道 C++ 发送结构

request - 根据我的请求设置日期值时,Google Protocol Buffers : c. toArray 不是一个函数

go - 如何使用OpenCensus跟踪称为函数的子函数?

sql - 如何使用 Go 函数更新 PostgresQL 表中的多个列

C++——指向结构数组的指针包含指向不起作用的类数组的指针

python-2.7 - python protobuf 安装为 windows

dart - 如何使用 dart-protobuf

戈朗 : How do I determine the number of lines in a file efficiently?

go - 如何将类型传递给 http 处理程序