我们正在使用proto3并尝试编写proto消息以生成golang结构,该结构可以被整理为具有特定结构的JSON输出。

数据需要具有混合类型的嵌套数组(特别是此处指定的vCard格式)

我们遇到的问题是生成具有混合类型的数组。例如,仅“vcardArray:[“vcard”,100],即具有字符串和int32的数组

如果我们这样使用Oneof:

message Vcard {
    oneof vcard {
        string name = 1;
        int32 value = 2;
    }
}

我们可以生成如下内容:
[
{"name":"vcard"},
{"int":100}
]

如果我们这样使用Any:
message VcardArray {
  repeated google.protobuf.Any vcard = 1;
}

我们可以生成:
[
    {
        type: "type.googleapis.com/google.protobuf.StringValue",
        value: "vcard"
    },
    {
        type: "type.googleapis.com/google.protobuf.Int32Value",
        value: 100
    },
]

我们期待下一个JSON:
 "vcardArray": [
    "vcard",
    [
        [ "version", {},"text","4.0"],
        [ "tel", {
            "pref":"1",
            "type":[
                "work",
                "voice"
                ]
            }
        ],
        [...],
        [...]
    ]
]

中心问题是,是否可以生成诸如[“vcard”,[...]]之类的混合元素的数组,如果可以,该怎么做?

最佳答案

您的问题有两个部分:

  • 如果有的话,可以使用struct混合结构数组生成json吗?
  • 您如何编写proto3以生成这样的go结构?

  • 第一个问题的答案是,您可以使用interface{}数组,这基本上意味着一个无类型值的数组。

    type Person struct {
        First   string        `json:"first_name"`
        Aliases []interface{} `json:"aliases"`
    }
    

    https://play.golang.org/p/sZfstLQAIf2

    现在,知道想要的go结构是什么,如何在proto中指定它?

    简短的答案是你不能。 (如果您好奇,可以看看* .pb.go文件是generated)

    但是,您可以编写一个函数,该函数采用protoc将为您生成的结构并将其转换为您自己的结构。这意味着您必须在添加或删除字段时使其保持最新状态。这也意味着protoc可以继续独立使用它的结构,而不是您可能需要生成json的方式。

    09-10 06:39
    查看更多