我们正在使用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”,[...]]之类的混合元素的数组,如果可以,该怎么做?
答案 0 :(得分:0)
您的问题有两个部分:
第一个问题的答案是,您可以使用<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title></title>
</head>
<body>
<form id="formEl">
<h2 id="question"></h2>
<input type="radio" id="rad1" name="rad" value='A'>
<label for="rad1" id="rad1Label"></label>
<input type="radio" id="rad2" name="rad" value='B'>
<label for="rad2" id="rad2Label"></label>
<input type="radio" id="rad3" name="rad" value='C'>
<label for="rad3" id="rad3Label"></label>
<input type="radio" id="rad4" name="rad" value='D'>
<label for="rad4" id="rad4Label"></label>
<button id="previous" type="button" class="userSelection">Previous</button>
<button id="next" type="button" class="userSelection">Next</button>
<button id="submit">Submit</button>
</form>
</body>
<script src = js/app.js></script>
</html>
数组,这基本上意味着一个无类型值的数组。
interface{}
https://play.golang.org/p/sZfstLQAIf2
现在,知道您想要的go结构是什么,如何在proto中指定它?
简短的答案是你不能。 (如果您感到好奇,可以看看* .pb.go文件是generated的样子)
但是,您可以编写一个函数,该函数采用protoc将为您生成的结构并将其转换为您自己的结构。这意味着您需要在添加或删除字段时保持最新状态。这也意味着protoc可以继续独立使用它的结构,而不是您可能需要如何生成json。