Minty
Minty

Reputation: 1241

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?

Upvotes: 0

Views: 2050

Answers (1)

tux21b
tux21b

Reputation: 94689

That doesn't make sense. There is no way for the JSON package to know what data should be decoded. This interface might be implemented by a struct{} type, an int type and maybe a struct{ Value1, Value2 int } type. Even worse, there might be other types as well, that are aren`t even part of your binary (missing imports, dead code elimination, etc.). So, which type do you expect to get back from JSON?

You probably need to find another way. For example, you could implement the json.Unmarshaler interface, unmarshal an identifier and use that identifier to unmarshal the following data into a concrete type. The switch statement that you will probably need for that, will also ensure that the concrete type is part of your binary (since you are using it).

But there is probably an easier solution. Your question doesn't tell what you want to archive though. Would it be enough to just marshal / unmarshal the name of the type as string?

Upvotes: 1

Related Questions