【问题标题】:while deserialising the protobuf as per .proto value is empty string而根据 .proto 值反序列化 protobuf 是空字符串
【发布时间】:2022-07-08 04:25:26
【问题描述】:

protobuf:

消息测试 {

      int16 a:1

message `testdata`{
       int16   b:1    `
       int16   c:2

repeated `testdata` `test_data`
}

}

dt=test() dt.a=11 dt1=d.testdata.add() dt1.b=2222 dt1.c=3333 发送=dt.SerializeToString()

现在反序列化代码如下:

t=test()
t.ParseFromString(send)
t1=t.testdata()
print(t1.test_data)----> empty string
print(t1.b)--> value is not printing as expected, its printing object name instead of value.

how to access the nested protobuf elements and any input or suggestions are welcome. 

【问题讨论】:

    标签: protocol-buffers


    【解决方案1】:

    我鼓励您阅读documentation

    您的protobuf 文件无效。

    与您所写的内容等效的可能是:

    example.proto:

    syntax = "proto3";
    
    message test {
    
        int32 a=1;
    
        message testdata {
            int32 b=1;
            int32 c=2;
        }
    
        repeated testdata test_data=2;
    }
    

    编译使用:

    protoc \
    --proto_path=${PWD} \
    --python_out=${PWD} \
    ${PWD}/example.proto
    

    示例 Python 代码(对我糟糕的变量命名选择表示歉意):

    import example_pb2
    f = example_pb2.test()
    f.a = 1
    
    g=f.test_data.add()
    g.b=1
    g.c=1
    
    g=f.test_data.add()
    g.b=2
    g.c=2
    
    g=f.test_data.add()
    g.b=3
    g.c=3
    
    print(f)
    
    x=f.SerializeToString()
    
    h=example_pb2.test()
    h.ParseFromString(x)
    print(h)
    

    产量:

    a: 1
    test_data {
      b: 1
      c: 1
    }
    test_data {
      b: 2
      c: 2
    }
    test_data {
      b: 3
      c: 3
    }
    
    a: 1
    test_data {
      b: 1
      c: 1
    }
    test_data {
      b: 2
      c: 2
    }
    test_data {
      b: 3
      c: 3
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多