I have been struggling to figure out the correct way to call upon an external struct for a map[string]struct
type when Unmarshalling JSON.
The code works when it is all within the same package, however if it is pulling an exported type, then there seems to be an error with the Unmarshal function.
package animals
type Bird struct {
Name string `json:"name"`
Description string `json:"description"`
}
package main
import (
"encoding/json"
"fmt"
"../animal"
)
func main() {
birdJson := `{"birds":{"name":"eagle","description":"bird of prey"}}`
var result map[string]animals.Bird //If Bird is external (animals.Bird) then the Unmarshal breaks
json.Unmarshal([]byte(birdJson), &result)
birds := result["birds"]
fmt.Printf("%s: %s", birds.Name, birds.Description)
// These entries will be the struct defaults instead of the values in birdJson
}
https://play.golang.org/p/e4FGIFath4s
So the code above works fine, but if the type Bird struct{}
is imported from another package then when I set map[string]animals.Bird
the json.Unmarshal doesn't work.
The workaround I have found is to set a new type like so: type Bird animals.Bird
. Is there a more elegant way of doing this?
This becomes a much bigger issue if future functions require the original animal.Bird struct
and will error when trying to use my new local type.
Update: I have updated the code above to show the non-working sample. The issue is that values will not be properly loaded into the map[string]animals.Bird
instead the default struct values will be loaded. I have to use a local package struct for the values to unmarshall correctly.
I apologize, the code above works, it turns out it was part of a rogue func (e *Bird) UnmarshalJSON(b []byte) error {}
I have wasted so much time on this :(