【发布时间】:2022-01-08 12:33:44
【问题描述】:
是否可以在不硬编码原始类型的情况下将 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)
}
在此示例中,我使用了对 Employee 的强制转换。但是如果我不知道类型怎么办?
当我只使用v 进行解组时,结构将被清零。
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v)
当我省略演员表时,我会得到一张地图。这是可以理解的
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v.Elem().Interface())
【问题讨论】:
-
仅仅因为它真的伤害了我的眼睛:为什么你有一个名为
new的变量?与更灵活的&Employee{}相比,您使用new(Employee)有什么意义? -
new(Something) 优于 &Something{}。它与非结构类型一致 + 它适用于该工作。
标签: json go reflection unmarshalling