{ "sendMsg":{"user":"ANisus","msg":"Trying to send a message"}, "say":"Hello"}0 O9 F7 J5 ?- }
有没有简单的方法可以用这个?"encoding/json"包做到这一点?! i+ [2 e7 {! l9 z% v G
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)} " F6 H2 y6 }" q4 L" v6 j) h0 Q
感谢您的建议/帮助!$ _4 s. j3 p: y- [. K
7 J9 v; l6 t( D5 I9 _& I w0 z 解决方案: 0 M0 }. h# b J 这可以通过将军map[string]json.RawMessage.. q a9 _. i" Z0 {4 j/ J1 ?
var objmap map[string]json.RawMessageerr := json.Unmarshal(data,&objmap)) \' E+ C6 W& C3 _0 [' E" V
进一步分析sendMsg,可执行以下操作: ; c8 e/ o# _* m" T" e
var s sendMsgerr = json.Unmarshal(objmap["sendMsg"],&s)& Z" G4 N- N& A$ s0 I/ I
对于say,您可以执行相同的操作并将其解组成字符串:) `6 c, U9 c+ }+ D4 e9 g
var str stringerr = json.Unmarshal(objmap["say"],&str) # N. L# L# L' Q; h
编辑:请记住,您还需要导出 sendMsg 正确解组结构中的变量。因此,您的结构定义将是:: e" x1 {1 `/ j H- c
type sendMsg struct User string Msg string} 4 o* ^% a" d( k' ?9 J$ z$ R