Saturday, 17 August 2013

Json Unmarshal reflect.Type

Json Unmarshal reflect.Type

Here is the code:
package main
import (
"fmt"
"encoding/json"
"reflect"
)
var(
datajson []byte
)
type User struct {
Name string
Type reflect.Type
}
func MustJSONEncode(i interface{}) []byte {
result, err := json.Marshal(i)
if err != nil {
panic(err)
}
return result
}
func MustJSONDecode(b []byte, i interface{}) {
err := json.Unmarshal(b, i)
if err != nil {
panic(err)
}
}
func Store(a interface{}) {
datajson = MustJSONEncode(a)
fmt.Println(datajson)
}
func Get(a []byte, b interface{}) {
MustJSONDecode(a, b)
fmt.Println(b)
}
func main() {
dummy := &User{}
david := &User{Name: "DavidMahon"}
typ := reflect.TypeOf(david)
david.Type = typ
Store(david)
Get(datajson, dummy)
}
I can successfully marshal reflect.Type but when I do the reverse, it
panics. I know reflect.Type is an interface. So what am I doing wrong
here? How can I store a reflect.Type value in json and then retrieve back
safely?

No comments:

Post a Comment