Is it possible to unmarshal JSON into a struct made from reflection without hardcoding the original type?
package main
import (
"fmt"
"encoding/json"
"reflect"
)
type Employee struct {
Firstname string `json:"firstname"`
}
func main() {
//Original struct
orig := new(Employee)
t := reflect.TypeOf(orig)
v := reflect.New(t.Elem())
//Reflected struct
new := v.Elem().Interface().(Employee)
// Unmarshal to reflected struct
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), &new)
fmt.Printf("%+v\n", new)
}
I used a cast to Employee
in this example. But what if i don't know the type?
When i just use v
for the unmarhaling the struct will be zeroed.
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v)
When I omit the cast I get a map. which is understandable
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v.Elem().Interface())
new
? And what's the point of your usingnew(Employee)
over the more flexible&Employee{}
? – Elias Van Ootegem