我的websocket服务器将接收和解组JSON数据.此数据将始终包含在具有键/值对的对象中.密钥字符串将充当值标识符,告诉Go服务器它是什么类型的值.通过知道什么类型的值,我可以继续JSON将值解组为正确的结构类型.
每个json对象可能包含多个键/值对.
示例JSON:
{
"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
"say":"Hello"
}
Run Code Online (Sandbox Code Playgroud)
有没有简单的方法使用"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 …Run Code Online (Sandbox Code Playgroud)