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)
}
我可以成功编码 reflect.Type
但是当我执行相反的操作时,它会出现困惑。我知道 reflect.Type
是一个接口(interface)。那我在这里做错了什么?如何将 reflect.Type
值存储在 json 中,然后安全地取回?
最佳答案
这没有意义。 JSON 包无法知道应解码哪些数据。此接口(interface)可能由 struct{}
类型、int
类型和可能的 struct{ Value1, Value2 int }
类型实现。更糟糕的是,可能还有其他类型,它们甚至不是二进制文件的一部分(缺少导入、删除死代码等)。那么,您希望从 JSON 返回哪种类型?
您可能需要寻找其他方法。例如,您可以实现 json.Unmarshaler
接口(interface),解码标识符并使用该标识符将以下数据解码为具体类型。您可能需要的 switch 语句还将确保具体类型是您的二进制文件的一部分(因为您正在使用它)。
但可能有更简单的解决方案。您的问题并没有说明您要存档的内容。仅将类型的名称编码/解码为字符串就足够了吗?
关于Json Unmarshal reflect.Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18291993/