簡體   English   中英

動態創建某種類型的結構並將JSON解組到該實例中

[英]Dynamically create struct of some type and unmarshal JSON into that instance

我在運行時創建一個struct實例。 該實例已成功創建,但我無法將JSON解組到其中。

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)
}

reflect.Indirect()返回一個reflect.Value類型的值,你應該將指向Test (其類型為*Test )的指針傳遞給json.Unmarshal()

只需使用Value.Interface()方法獲取指向reflect.New()返回的Test結構的指針,如下所示:

f := reflect.New(elType).Interface()
b := []byte(`{"name": "go"}`)
err := json.Unmarshal(b, f)

有了這個工作,輸出將是:

<nil> &{go}

注意f將是interface{}類型,保持*Test指針值。 如果需要struct值,可以使用類型斷言,如下所示:

t := *f.(*Test)
fmt.Println(t)

這打印:

{go}

試試Go Playground上的例子。

我認為您不需要使用反射,而是可以執行以下操作:

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

func create(a interface{}) {
    b := []byte(`[{"name": "go"}]`)

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

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

代碼reflect.Indirect(reflect.New(elType))返回一個reflect.Value代替的具體值elType 當你解組它時,json包會查看沒有字段Namereflect.Value結構,所以它什么都不做。

相反,您應該使用reflect.Value.Interface()將其轉換為保持具體類型的interface{}

游樂場: https//play.golang.org/p/sW9mJd8fKMb

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM