我的 websocket 服务器接收和解组 JSON 数据。此数据将始终包含在具有键/值对的对象中。key-string 将作为值标识符告诉 Go 服务器是什么样的值?我可以通过知道什么样的值继续 JSON 将值解组成正确类型的结构。# V2 v* v: ^- d7 h4 T
每个 json-object 可能包含多个键/值对。 ; C- e- H m' d; Z2 j示例 JSON: 3 b/ G( h) g/ V$ H0 s* x8 j' m
{ "sendMsg":{"user":"ANisus","msg":"Trying to send a message"}, "say":"Hello"} 9 J" a8 q& Z6 b; ^! _: p9 o' p
package mainimport "encoding/json" "fmt")// the struct for the value of a "sendMsg"-commandtype sendMsg struct user string msg string}// The type for the value of a "say"-commandtype say stringfunc 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)} 9 ]: w3 q- v+ L M: Y3 [1 }6 v
感谢您的建议/帮助! 9 ] C; J" }3 g t' H& o! V # n- R' ^' S% n. l7 ]) V! S 解决方案: % d9 p4 Y* Q/ I# Y 这可以通过将军map[string]json.RawMessage.5 X4 I+ n i3 \( C
var objmap map[string]json.RawMessageerr := json.Unmarshal(data,&objmap)% ^: E' v, y5 ~: i( x* E
进一步分析sendMsg,可执行以下操作:% Y" Q. E- [$ J2 \0 D# _6 ~
var s sendMsgerr = json.Unmarshal(objmap["sendMsg"],&s) . H% n3 y6 t: n& b