How to parse JSON in golang without unmarshaling twice

前端 未结 3 1416
甜味超标
甜味超标 2021-01-06 17:16

I\'ve got a web socket connection that sends different types of messages in a JSON object, and I want to unmarshal the contents into some known structs. To do this, I figur

3条回答
  •  情深已故
    2021-01-06 17:53

    One solution is to partially unmarshal the data by unmarshalling the values into a json.RawMessage instead of an interface{}

    var myMap map[string]json.RawMessage
    

    Later in the switch, which still is required, you do not need to marshal. Just do:

    err = json.Unmarshal(v, &myAck)
    

    Playground: https://play.golang.org/p/NHd3uH5e7z

提交回复
热议问题