是否有可能解开JSON到反射而不是硬编码原始类型的结构?Unmarshal json反射结构
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)
}
在这个例子中,我使用了cast到Employee
。但是如果我不知道这种类型呢?
当我只使用v
进行非标注时,结构将被清零。
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v)
当我省略演员时,我得到一张地图。这是可以理解
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v.Elem().Interface())
只因为它是真的伤害了我的眼睛:为什么你有一个叫'新'的变种?在更灵活的&Employee {}'上使用'new(Employee)'有什么意义? –