解组时接受原型结构中的动态键 JSON
Accept dynamic keys in proto struct when unmarshalling JSON
我的 Proto 文件看起来像这样:
message Test {
Service services = 1;
}
message Service {
string command = 1;
string root = 2;
}
这个 .proto 可以支持这样的 json:
{
"services": {
"command": "command2",
"root": "/"
},
}
但是,我想管理一个如下所示的 json:
{
"services": {
"service1": {
"command": "command1",
"root": "/"
},
"service2": {
"command": "command2",
"root": "/"
},
},
}
因此,这里所有的服务都将具有共同的结构,但键名会有所不同(即 "service1"
、"service2"
)
现在,我想从 test.json 读取数据并解组它:
var test *Test
err := json.Unmarshal([]byte(file), &test)
我应该在 .proto
中做哪些更改才能成功解组此 json?
使用原型 map:
message Test {
map<string, Service> services = 1;
}
message Service {
string command = 1;
string root = 2;
}
Go 中的原型映射是 compiled 到 map[K]V
,因此在这种情况下 map[string]*Service
,这是使用任意键建模 JSON 的推荐方法。
这将给出以下输出:
services:{key:"service1" value:{command:"command1" root:"/"}} services:{key:"service2" value:{command:"command2" root:"/"}}
示例程序:
package main
import (
"encoding/json"
"example.com/pb"
"fmt"
)
const file = `{
"services": {
"service1": {
"command": "command1",
"root": "/"
},
"service2": {
"command": "command2",
"root": "/"
}
}
}
`
func main() {
test := &pb.Test{}
err := json.Unmarshal([]byte(file), test)
if err != nil {
panic(err)
}
fmt.Println(test)
}
我的 Proto 文件看起来像这样:
message Test {
Service services = 1;
}
message Service {
string command = 1;
string root = 2;
}
这个 .proto 可以支持这样的 json:
{
"services": {
"command": "command2",
"root": "/"
},
}
但是,我想管理一个如下所示的 json:
{
"services": {
"service1": {
"command": "command1",
"root": "/"
},
"service2": {
"command": "command2",
"root": "/"
},
},
}
因此,这里所有的服务都将具有共同的结构,但键名会有所不同(即 "service1"
、"service2"
)
现在,我想从 test.json 读取数据并解组它:
var test *Test
err := json.Unmarshal([]byte(file), &test)
我应该在 .proto
中做哪些更改才能成功解组此 json?
使用原型 map:
message Test {
map<string, Service> services = 1;
}
message Service {
string command = 1;
string root = 2;
}
Go 中的原型映射是 compiled 到 map[K]V
,因此在这种情况下 map[string]*Service
,这是使用任意键建模 JSON 的推荐方法。
这将给出以下输出:
services:{key:"service1" value:{command:"command1" root:"/"}} services:{key:"service2" value:{command:"command2" root:"/"}}
示例程序:
package main
import (
"encoding/json"
"example.com/pb"
"fmt"
)
const file = `{
"services": {
"service1": {
"command": "command1",
"root": "/"
},
"service2": {
"command": "command2",
"root": "/"
}
}
}
`
func main() {
test := &pb.Test{}
err := json.Unmarshal([]byte(file), test)
if err != nil {
panic(err)
}
fmt.Println(test)
}