JSON decoding in Go changes the object type? -
i trying build library can read multiple different types of objects out of json files (the actual library pulls them out of couchdb, purposes of it's loading them json).
my library doesn't know concrete type of object being loaded, hence "createobject()" call below (which satisfied interface in real code).
i'm having problem when try cast object created createobject() call concrete type (mytype in example) i'm getting panic:
panic: interface conversion: interface map[string]interface {}, not main.mytype
i'd know i'm going wrong here, or whether there's more go-like way should approaching problem. if doing in java i'd using generics , expect straightforward.
note if comment out json.newdecoder... line code works (prints out blank line, expected). implies happening in decode operation.
runnable example follows:
package main import ( "encoding/json" "fmt" "strings" ) type mytype struct { name string `json:"name"` age int32 `json:"age"` } func createobject() interface{} { return mytype{} } func loadjsondata() interface{} { obj := createobject() jsonstr := `{"name":"person", "age":30}` json.newdecoder(strings.newreader(jsonstr)).decode(&obj) return obj } func main() { obj := loadjsondata() // works reason // y := obj.(map[string]interface{}) // fmt.println(y["name"]) // causes panic x := obj.(mytype) fmt.println(x.name) }
you should use pointer instead of struct:
func createobject() interface{} { return &mytype{} // here } ... // causes panic x := obj.(*mytype) // , there fmt.println(x.name)
enjoy: http://play.golang.org/p/vjjaqlq_vh
if want read more it, consider following thread: golang fails parse json reflection created object
Comments
Post a Comment