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 figure I should do the following:
Step 1) Unmarshal the JSON into a generic map[string]interface{}
Step 2) Find the key I'm looking for
Step 3) Try to cast the value into one of my types (this fails)
Step 3 alternate) json marshal this value and unmarshal it to my known struct
If I try to use myStruct, ok := value.(myType) it will fail, but if I json.marshal(value) and then json.unmarshal to myStruct, it works just fine. Is that how I'm supposed to do this? Going json-> map[string]interface{} -> json -> myStruct seems redundant to me.
Sample code:
https://play.golang.org/p/to_0Id_ja9
package main
import (
"encoding/json"
"fmt"
)
type Ping struct {
Ping string `json:"ping"`
}
type Ack struct {
Messages []Message `json:"messages"`
}
type Message string
func main() {
testJSON := []byte(`{"ack":{"messages":["Hi there","Hi again"]}}`)
var myAck = Ack{}
var myMap map[string]interface{}
err := json.Unmarshal(testJSON, &myMap)
if err != nil {
fmt.Println("error unmarshalling: ", err)
}
for k, v := range myMap {
fmt.Printf("key: %s, value: %s \n", k, v)
switch k {
case "ping":
fmt.Println(k, " is a ping", v)
case "ack":
fmt.Println(k, " is an ack containing a message list")
ackjson, err := json.Marshal(v)
if err != nil {
fmt.Println("marshal error: ", err)
}
err = json.Unmarshal(ackjson, &myAck)
if err != nil {
fmt.Println("unmarshal error", err)
} else {
fmt.Println("New ack object: ", myAck)
}
default:
fmt.Printf("%s is of a type (%T) I don't know how to handle", k, v)
}
}
}
0 answers
Hot tools Tags
Hot Questions
Popular tool
vc9-vc14 (32+64 bit) runtime library collection (link below)
Download the collection of runtime libraries required for phpStudy installation
VC9 32-bit
VC9 32-bit phpstudy integrated installation environment runtime library
PHP programmer toolbox full version
Programmer Toolbox v1.0 PHP Integrated Environment
VC11 32-bit
VC11 32-bit phpstudy integrated installation environment runtime library
SublimeText3 Chinese version
Chinese version, very easy to use
Hot Topics
20416
7
13574
4






