簡體   English   中英

Go中的JSON解碼會更改對象類型嗎?

[英]JSON decoding in Go changes the object type?

我正在嘗試構建一個庫,該庫可以從JSON文件中讀取多種不同類型的對象(實際的庫會將它們從長沙發中拉出,但出於此目的,它是從JSON加載它們的)。

我的庫對正在加載的對象的具體類型一無所知,因此下面的“ CreateObject()”調用(由實際代碼中的接口來滿足)。

我遇到一個問題,當我嘗試將由CreateObject()創建的對象強制轉換回我的具體類型(在示例中為MyType)時,我會感到恐慌:

panic: interface conversion: interface is map[string]interface {}, not main.MyType

我想知道我在哪里出問題了,或者我是否還有另一種類似的方式來解決這個問題。 如果我使用Java進行操作,則將使用泛型,並且希望它很簡單。

請注意,如果我注釋掉json.NewDecoder ...行,那么代碼將起作用(按預期方式打印出空白行)。 這意味着在解碼操作中發生了一些事情。

可運行的示例如下:

package main

import (
    "encoding/json"
    "fmt"
    "strings"
)

type MyType struct {
    Name string `json:"name"`
    Age  int32  `json:"age"`
}

func CreateObject() interface{} {
    return MyType{}
}

func LoadJsonData() interface{} {
    obj := CreateObject()
    jsonStr := `{"name":"Person", "age":30}`
    json.NewDecoder(strings.NewReader(jsonStr)).Decode(&obj)

    return obj
}

func main() {

    obj := LoadJsonData()

    // This works for some reason
    // y := obj.(map[string]interface{})
    // fmt.Println(y["name"])

    // This causes a panic
    x := obj.(MyType)
    fmt.Println(x.Name)
}

操場

您應該使用指針而不是struct:

func CreateObject() interface{} {
    return &MyType{} // here
}

...

// This causes a panic
x := obj.(*MyType) // and there
fmt.Println(x.Name)

欣賞: http//play.golang.org/p/vJjaQlq_vh

如果您想了解更多信息,請考慮以下線程: golang無法為反射創建的對象解析json

暫無
暫無

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

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