最佳答案
我的 websocket 服务器将接收和解组 JSON 数据。此数据将始终包装在具有键/值对的对象中。键字符串将作为值标识符,告诉 Go 服务器它是什么类型的值。通过了解值的类型,我可以继续 JSON 将值解组为正确的 struct 类型。
每个 json-object 可能包含多个键/值对。
例子:
{
"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)
}
谢谢你的建议/帮助!