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) } 

playground

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

Popular posts from this blog

mysql - FireDac error 314 - but DLLs are in program directory -

git - How to list all releases of public repository with GitHub API V3 -

c++ - Getting C2512 "no default constructor" for `ClassA` error on the first parentheses of constructor for `ClassB`? -