I have a question about decoding arbitrary JSON objects/messages in Go.. Lets say for example you have three wildly different JSON objects (aka messages) that you can receive on an http connection, lets call them for sake of illustration:
{ home : { some unique set of arrays, objects, fields, and arrays objects } }
and
{ bike : { some unique set of arrays, objects, fields, and arrays objects } }
and
{ soda : { some unique set of arrays, objects, fields, and arrays objects } }
What I am thinking is you could decode these, from an http connection in to a map of interfaces such as:
func httpServerHandler(w http.ResponseWriter, r *http.Request) {
message := make(map[string]interface{})
decoder := json.NewDecoder(r.Body)
_ = decoder.Decode(&message)
Then do an if, else if block to look for valid JSON messages
if _, ok := message["home"]; ok {
// Decode interface{} to appropriate struct
} else if _, ok := message["bike"]; ok {
// Decode interface{} to appropriate struct
} else {
// Decode interface{} to appropriate struct
}
Now in the if block I can make it work if I re-decode the entire package, but I was thinking that is kind of a waste since I have already partially decoded it and would only need to decode the value of the map which is an interface{}, but I can not seem to get that to work right.
Redecoding the entire thing works though, if I do something like the following where the homeType for example is a struct:
var homeObject homeType
var bikeObject bikeType
var sodaObject sodaType
Then in the if block do:
if _, ok := message["home"]; ok {
err = json.Unmarshal(r.Body, &homeObject)
if err != nil {
fmt.Println("Bad Response, unable to decode JSON message contents")
os.Exit(1)
}
So without re-decoding / unmarshal-ing the entire thing again, how do you work with the interface{} in a map?