简体   繁体   中英

JSON decoding in Go changes the object type?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM