lundi 18 juin 2018

golang dynamicly create struct of some type and unmarshal json into that instance

I try to create an struct instance at run time. The instance has been created successfully, but I can't unmarshal json into it.

type Test struct {
    Name string `json:"name,omitempty"`
}

func create(a interface{}) {
    aType := reflect.TypeOf(a).Elem()
    elType := aType.Elem()

    f := reflect.Indirect(reflect.New(elType))

    b := []byte(`{"name": "go"}`)

    err := json.Unmarshal(b, &f)
    fmt.Println(err, f)
}

func main() {
    l := []Test{}
    create(&l)
}





Aucun commentaire:

Enregistrer un commentaire