首页 > 解决方案 > 访问嵌套 proto 字段内的数据

问题描述

首先,如果标题措辞不当,请见谅。我不确定我在这里做什么,因为这是我第一次使用 protobuf。

我使用 protoc 解码 .bin 文件得到以下输出

1: 1540
2: "test"
3: 186
4: 10041
5: "test2"
11: 1
12: 1
13: 1
14: 1
15: 1
16: 1
17: 1
18: 1
19: 1
101 {
  1 {
    1: 1540
    2: 379
    3: 60
    4: 0
    5: 1553862415000
  }
}

我正在制作一个带有以下消息的原型文件

syntax = "proto2";

message Profile {
  required int32 id = 1;
  required string name = 2;
  required int32 rank = 3;
  required string description = 5;
  required string test = 101;
}

如何设置消息以便我可以访问内部的数据,101因为它内部有嵌套字段?

标签: pythonprotocol-buffers

解决方案


查看解码的消息,看起来它真的是从类似的东西生成的

message Profile {
  (...)
  required Level2 test = 101;
}

message Level2 {
  optional Level3 nested = 1;
}

message Level3 {
  optional int32 field1 = 1;
  optional int32 field2 = 2;
  optional int32 field3 = 3;
  optional int32 field4 = 4;
  optional int32 field5 = 5;
}

当然,很难说int32类型是否正确,或者这些字段是否应该重复。

如果您想访问这些字段,您可以将消息定义更改为上述内容。

如果您不想解析该字段(即,将其作为简单的序列化表示返回,您可以将其键入为bytes

message Profile {
  (...)
  required bytes test = 101;
}

推荐阅读