Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmarshall into an interface type

I expected below code to print an object of type struct J, however it prints a map object of type map[string]interface{}. I can feel why it acts like that, however when I run, reflect.ValueOf(i).Kind(), it returns Struct, so it kinda gives me the impression that Unmarshal method should return type J instead of a map. Could anyone enlighten me ?

type J struct {
    Text string
}

func main() {
    j := J{}
    var i interface{} = j

    js := "{\"Text\": \"lala\"}"


    json.Unmarshal([]byte(js), &i)

    fmt.Printf("%#v", i)

}
like image 465
Ozum Safa Avatar asked Oct 26 '25 20:10

Ozum Safa


1 Answers

The type you're passing into Unmarshal is not *J, you're passing in an *interface{}.

When the json package reflects what the type is of the pointer it received, it sees interface{}, so it then uses the default types of the package to unmarshal into, which are

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

There is almost never a reason to use a pointer to an interface. If you find yourself using a pointer to an interface, and you don't know exactly why, then it's probably a mistake. If you want to unmarshal into J, then pass that in directly. If you need to assign that to an intermediary interface, make sure you use a pointer to the original value, not a pointer to its interface.

http://play.golang.org/p/uJDFKfSIxN

j := J{}
var i interface{} = &j

js := "{\"Text\": \"lala\"}"

json.Unmarshal([]byte(js), i)

fmt.Printf("%#v", i)
like image 111
JimB Avatar answered Oct 28 '25 12:10

JimB