我的 websocket 服务器将接收和解组 JSON 数据。此数据将始终包含在具有键/值对的对象中。键字符串将充当值标识符,告诉 Go 服务器它是什么类型的值。通过知道什么类型的值,我可以继续使用 JSON 将值解组为正确的结构类型。
每个 json 对象可能包含多个键/值对。
示例 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)
}
感谢您的任何建议/帮助!