我的 websocket 服务器将接收和解码 JSON 数据。此数据将始终包含在具有键/值对的对象中。键字符串将充当值标识符,告诉 Go 服务器它是什么类型的值。通过知道什么类型的值,我可以继续 JSON 将值解码为正确的结构类型。
每个 json-object 可能包含多个键/值对。
示例 JSON:
{
"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
"say":"Hello"
}
有没有什么简单的方法可以使用 "encoding/json"
包来做到这一点?
package main
import (
"encoding/json"
"fmt"
)
// the struct for the value of a "sendMsg"-command
type sendMsg struct {
user string
msg string
}
// The type for the value of a "say"-command
type say string
func main(){
data := []byte(`{"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},"say":"Hello"}`)
// This won't work because json.MapObject([]byte) doesn't exist
objmap, err := json.MapObject(data)
// This is what I wish the objmap to contain
//var objmap = map[string][]byte {
// "sendMsg": []byte(`{"user":"ANisus","msg":"Trying to send a message"}`),
// "say": []byte(`"hello"`),
//}
fmt.Printf("%v", objmap)
}
感谢您的任何建议/帮助!
最佳答案
这可以通过解码到 map[string]json.RawMessage
来完成。
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
要进一步解析 sendMsg
,您可以执行以下操作:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
对于say
,你可以做同样的事情并解码成一个字符串:
var str string
err = json.Unmarshal(objmap["say"], &str)
编辑:请记住,您还需要导出 sendMsg 结构中的变量以正确解码。所以你的结构定义是:
type sendMsg struct {
User string
Msg string
}
关于json - 部分 JSON 在 Go 中解码为 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066946/