我的 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?
uj5u.com熱心網友回復:
使用原始地圖:
message Test {
map<string, Service> services = 1;
}
message Service {
string command = 1;
string root = 2;
}
在原地圖編譯到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)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364748.html
