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
You will want to create a struct which contains all keys you might receive, then unmarshal once, finally based on which keys are nil
you can decide what kind of packet you got.
The example below displays this behavior: https://play.golang.org/p/aFG6M0SPJs
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Ack struct {
Messages []string `json:"messages"`
}
type Packet struct {
Ack * Ack `json:"ack"`
Ping * string `json:"ping"`
}
func runTest(testJSON []byte) {
var p = Packet{}
err := json.Unmarshal(testJSON, &p)
if err != nil {
fmt.Println("error unmarshalling: ", err)
}
if (p.Ack != nil) {
fmt.Println("Got ACK: ", strings.Join(p.Ack.Messages, ", "));
} else if (p.Ping != nil){
fmt.Println("Got PING");
}
}
func main() {
tests := [][]byte{
[]byte(`{"ack":{"messages":["Hi there","Hi again"]}}`),
[]byte(`{"ping": "Are you there?"}`),
}
for _, test := range tests {
runTest(test)
}
}