回答

收藏

在 Go 中部分 JSON 解组为地图

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

我的 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
有没有简单的方法可以用这个?"encoding/json"包做到这一点?
- h* `' r: ?% m: e0 q
    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
对于say,您可以执行相同的操作并将其解组成字符串:
( Y( S, n* t5 W* j9 o1 T1 Y
    var str stringerr = json.Unmarshal(objmap["say"],&str)3 ^- W% n+ i9 k, @
编辑:请记住,您还需要导出 sendMsg 正确解组结构中的变量。因此,您的结构定义将是:
! F+ K. @" g' K5 [
    type sendMsg struct    User string    Msg  string}
    4 r3 f& Y/ n/ o$ G0 I2 p0 q
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则