解组json来反映结构 [英] Unmarshal json to reflected struct
问题描述
是否有可能将JSON解组到反向构造的结构中而不对原始类型进行硬编码?
package main
import(
fmt
encoding / json
reflect
)
类型Employee struct {
名字字符串`json:firstname`
}
func main(){
//原始结构体
orig:= new(Employee)
t:= reflect.TypeOf(orig)
v:= reflect.New(t.Elem())
//反射结构
new:= v.Elem()。Interface()。(Employee)
//解组为反射结构
json.Unmarshal([] byte({\firstname \:\bender \}),& new)
fmt.Printf(%+ v\\\
,new)
}
在本例中,我使用了一个强制类型转换为 Employee
。但是如果我不知道这种类型呢?
当我使用 v
作为非标记时,结构将被清零。
json.Unmarshal([] byte({\firstname \:\bender \}} ),v)
当我省略演员时,我得到一张地图。这是可以理解的
json.Unmarshal([] byte({\firstname \:\bender \\ }),v.Elem().Interface())
new:= v.Elem() .Interface()
然后当你把地址解组时, 如果不是直接使用指针引用来获取 游乐场: https://play.golang.org/ p / lTBU-1PqM4 Is it possible to unmarshal JSON into a struct made from reflection without hardcoding the original type? I used a cast to When i just use When I omit the cast I get a map. which is understandable
The problem here is that if you omit the type assertion here: The Then when you take the address to unmarshal, the type of You can avoid the type assertion if instead of getting the Playground: https://play.golang.org/p/lTBU-1PqM4 这篇关于解组json来反映结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!接口{}
类型。
& new
是 * interface {}
(指向接口{}的指针),并且解组无法按预期工作。 p>
Elem()
,那么可以避免类型断言。 p>
func main(){
//原结构
orig:= new(Employee)
t:= reflect.TypeOf(orig)
v:= reflect.New(t.Elem())
//反射指针
newP:= v.Inte rface()
//解组为反射结构指针
json.Unmarshal([] byte({\firstname \:\bender \}) ,newP)
fmt.Printf(%+ v \ n,newP)
}
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
in this example. But what if i don't know the type? v
for the unmarhaling the struct will be zeroed. json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v)
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v.Elem().Interface())
new := v.Elem().Interface()
new
is inferred to have a interface{}
type.&new
is *interface{}
(pointer to interface{}) and unmarshal does not work as you expect.Elem()
you work directly with the pointer reference.func main() {
//Original struct
orig := new(Employee)
t := reflect.TypeOf(orig)
v := reflect.New(t.Elem())
// reflected pointer
newP := v.Interface()
// Unmarshal to reflected struct pointer
json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), newP)
fmt.Printf("%+v\n", newP)
}