解组 JSON 时接受 proto 结构中的动态键

我的 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?


慕的地6264312
浏览 87回答 1
1回答

温温酱

使用原型图:message Test {&nbsp; &nbsp; map<string, Service> services = 1;}message Service {&nbsp; &nbsp; string command = 1;&nbsp; &nbsp; string root = 2;}proto map 是在 Go中编译的,因此在这种情况下,这是使用任意键对 JSON 建模的推荐方法。map[K]Vmap[string]*Service这将给出以下输出:services:{key:"service1" value:{command:"command1" root:"/"}} services:{key:"service2" value:{command:"command2" root:"/"}}示例程序:package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "example.com/pb"&nbsp; &nbsp; "fmt")const file = `{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "services": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "service1": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "command": "command1",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "root": "/"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "service2": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "command": "command2",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "root": "/"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }`func main() {&nbsp; &nbsp; test := &pb.Test{}&nbsp; &nbsp; err := json.Unmarshal([]byte(file), test)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(test)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go