我正在嘗試構建一個可以從 JSON 文件中讀取多種不同類型對象的庫(實際庫將它們從 couchdb 中提取出來,但為此目的,它是從 json 加載它們)。我的庫對加載的具體對象類型一無所知,因此下面的“CreateObject()”調用(由實際代碼中的接口滿足)。我遇到了一個問題,當我嘗試將 CreateObject() 調用創(chuàng)建的對象轉換回我的具體類型(示例中的 MyType)時,我感到恐慌:panic: interface conversion: interface is map[string]interface {}, not main.MyType我想知道我在這里哪里出錯了,或者是否有另一種更類似的方式來解決這個問題。如果我在 Java 中做這件事,我會使用泛型并且希望它很簡單。請注意,如果我注釋掉 json.NewDecoder... 行,則代碼有效(按預期打印出一個空行)。這意味著在解碼操作中發(fā)生了一些事情??蛇\行示例如下:package mainimport ( "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)}
- 1 回答
- 0 關注
- 155 瀏覽
添加回答
舉報
0/150
提交
取消