json - 通过 Go 在 Protocol Buffers v3 的 oneOf 字段中使用结构

标签 json go protocol-buffers grpc

因此尝试同时使用 Protocol Buffers v3 和 Go(两者都是新的)。

example.proto

syntax = "proto3";

package test;

import "google/protobuf/timestamp.proto";

message Metadata {
    uint64 userID = 2;
    google.protobuf.Timestamp time= 3; 
}

//SignOff when user logs out of Glory
message SignOff {
    Metadata metadata =1;
}

//SignOn when user logs into Glory
message SignOn {
    Metadata metadata =1;
}

message EventWrapper {
    oneof event {
        SignOff signOff = 1;
        SignOn signOn = 2;
    }
}

protoc 转换并在 Go 中使用

now, _ := ptypes.TimestampProto(time.Now())
event := &pb_test.EventWrapper{
    Event: &pb_test.EventWrapper_SignOn{
        SignOn: &pb_test.SignOn{
            Metadata: &pb_test.Metadata{
                UserID: 1234,
                Time:   now,
            },
        },
    },
}
protoBytes, err := proto.Marshal(event)
if err != nil {
    log.Fatal(err)
}
log.Println(len(protoBytes) == 0)

jsonBytes, _ = json.MarshalIndent(event, "", "\t")
log.Println(string(jsonBytes))

输出显示 JSON 正确,但 protobuf 编码的字节数组为空。

{
    "Event": {
        "SignOn": {
            "metadata": {
                "userID": 1234,
                "time": {
                    "seconds": 1491143507,
                    "nanos": 654053400
                }
            }
        }
    }
}

目的是让这些(repeated *EventWrapper)的数组通过 gRPC 沿着线路发送,但目前个别的不起作用。 protobuf Language Guide没有说任何关于不允许的结构。有什么我想念的吗?

最佳答案

Protocol Buffer 文档中没有任何内容表明 oneof 不能是结构,事实上 exampleunion 字段生成结构。

我推荐使用 gogo ,我个人曾将其用于以前的商业项目。具体来说,使用 protoc-gen-gogoslick

参见 this section安装必要的包,然后为您的项目运行以下命令

protoc --gogoslick_out=Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types:. example.proto

关于json - 通过 Go 在 Protocol Buffers v3 的 oneOf 字段中使用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43169640/

相关文章:

json - 在 JSON 中存储记录数组

c# - json 错误错误的 JSON 转义序列

string - 从 Go 中的 slice 中删除字符串

arrays - 在 Golang 中重新 slice

c++ - 使用 Protocol Buffers 更快反序列化的建议

javascript - qTip2 - 一次加载所有 AJAX 站点

javascript - 通过搜索从 JSON 填充表

xml - 将 Go 结构体转换为字符串

c++ - protobuf 3 中的原始类型

python - 反序列化消息而不将整个文件加载到内存中?