回答

收藏

在 Go 中部分 JSON 解组为地图

技术问答 技术问答 360 人阅读 | 0 人回复 | 2023-09-12

我的 websocket 服务器接收和解组 JSON 数据。此数据将始终包含在具有键/值对的对象中。key-string 将作为值标识符告诉 Go 服务器是什么样的值?我可以通过知道什么样的值继续 JSON 将值解组成正确类型的结构。
! t% X- m' D" }, G每个 json-object 可能包含多个键/值对。
7 M9 }- B( _) M9 B! m  a8 B示例 JSON:
  `# x2 J0 L9 s& m5 @
    {    "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
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则