Json Unmarshal reflect.Type

标签 json reflection go

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)
}

我可以成功编码 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/

相关文章:

php - 为什么我无法将 CSV 文件中的新项目添加到 PHP 中 while 循环内的数组中?

java - 为什么它说它是一个字符串?

reflection - 如何实现 GetStringValueByField(n interface{}, field_name string) string

c# - 使用反射来分析参数及其值

go - 如何为谷歌自动生成的库初始化一个包含 slice 的结构

go - 是否可以使用 Go 对 python/php/perl 进行扩展?

javascript - 使用 postgres 将行减少为 json 键/值对

c# - 反射(reflection):FindMembers 返回空

go - 主线程永远不会屈服于 goroutine

javascript - JQuery 从 REST 和 JSON 获取数据源