dongxinche1264
2015-08-19 13:02
浏览 41

Go中的JSON解码会更改对象类型吗?

I am trying to build a library that can read multiple different types of objects out of JSON files (the actual library pulls them out of couchdb, but for the purposes of this it's loading them from json).

My library doesn't know anything about the concrete type of object being loaded, hence the "CreateObject()" call below (which is satisfied by an interface in the real code).

I'm having a problem that when I try to cast the object created by the CreateObject() call back to my concrete type (MyType in the example) I'm getting a panic:

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

I'd like to know where I'm going wrong here, or whether there's another more go-like way I should be approaching this problem. If I was doing it in Java I'd be using generics and would expect it to be straightforward.

Note that if I comment out the json.NewDecoder... line then the code works (prints out a blank line, as expected). This implies something is happening in the Decode operation.

Runnable example follows:

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

Playground

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanli9591 2015-08-19 13:18
    已采纳

    You should use pointer instead of struct:

    func CreateObject() interface{} {
        return &MyType{} // here
    }
    
    ...
    
    // This causes a panic
    x := obj.(*MyType) // and there
    fmt.Println(x.Name)
    

    Enjoy: http://play.golang.org/p/vJjaQlq_vh

    If you want to read more about it, consider the following thread: golang fails to parse json for reflection created object

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题