gpt4 book ai didi

go - Protocol Buffer 序列化 Golang

转载 作者:行者123 更新时间:2023-12-03 02:37:29 25 4
gpt4 key购买 nike

我正在使用DialogFlow V2 official GoLang SDK 。在我的 webhook 中,我返回一个有效负载,这是我使用函数 GetWebhookPayload() 获得的。 .

这将返回 *google_protobuf4.Struct 。我想将此结构转换为 map[string]interface{}。这怎么可能?

这是结构体序列化后的样子:

"payload": {
"fields": {
"messages": {
"Kind": {
"ListValue": {
"values": [
{
"Kind": {
"StructValue": {
"fields": {
"title": {
"Kind": {
"StringValue": "Hi! How can I help?"
}
},
"type": {
"Kind": {
"StringValue": "message"
}
}
}
}
}
}
]
}
}
}
}

我本质上需要的是对其进行序列化:

"payload": {
"messages": [
{
"title": "Hi! How can I help?",
"type": "message"
}
]
}

最佳答案

这可以使用 jsonpb 来解决.

package main

import (
"bytes"
"encoding/json"

"github.com/golang/protobuf/jsonpb"
)

func main() {
...

payload := qr.GetWebhookPayload()
b, marshaler := bytes.Buffer{}, jsonpb.Marshaler{}
if err := marshaler.Marshal(&b, payload.GetFields()["messages"]); err != nil {
// handle err
}

msgs := []interface{}{}
if err := json.Unmarshal(b.Bytes(), &msgs); err != nil {
// handle err
}

// msgs now populated
}

关于go - Protocol Buffer 序列化 Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com