解散反映价值

Min*_*nty 5 reflection json go unmarshalling

这是代码

package main

import (
    "fmt"

    "encoding/json"
    "reflect"
)

var (
    datajson []byte
    //ref mapp
)

type mapp map[string]reflect.Type

type User struct {
    Name string
    //Type map[string]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{}) {
    objType := reflect.TypeOf(b).Elem()
obj := reflect.New(objType)
//fmt.Println(obj)
MustJSONDecode(a, &obj)
fmt.Printf("%s", obj)
    }

func main() {

    dummy := &User{}
    david := User{Name: "DavidMahon"}

    Store(david)
    Get(datajson, dummy)

}
Run Code Online (Sandbox Code Playgroud)

在Get函数中

func Get(a []byte, b interface{}) {
    objType := reflect.TypeOf(b).Elem()
obj := reflect.New(objType)
//fmt.Println(obj)
MustJSONDecode(a, &obj)
fmt.Printf("%s", obj)
    }
Run Code Online (Sandbox Code Playgroud)

我无法将json解组为底层对象类型.

这里有什么不对?我被困在这里了.非常简单但很难弄明白的东西.

谢谢

UPDATE ::此问题的目标是检索Get函数中传递的完全形式的对象类型.

尼克在下面的评论中提到的方法并没有让我得到我之前尝试过的实际对象.我可以在这样的地图中检索数据(即使对象下面有递归对象)

func Get(a []byte) {
    var f interface{}

    //buf := bytes.NewBuffer(a)
    //v := buf.String()
    //usr := &User{}

    MustJSONDecode(a, &f)
    fmt.Printf("\n %v \n", f)
}
Run Code Online (Sandbox Code Playgroud)

但是我需要的实际对象不仅仅是数据.像Unmarshall 那样user := &User{"SomeName"}我需要user对象的地方.诀窍在某个地方反思,但不知道如何.

Nic*_*ood 5

我很困惑你为什么要这样做,但这是解决方法

func Get(a []byte, b interface{}) {
    objType := reflect.TypeOf(b).Elem()
    obj := reflect.New(objType).Interface()
    //fmt.Println(obj)
    MustJSONDecode(a, &obj)
    fmt.Printf("obj = %#v\n", obj)
}
Run Code Online (Sandbox Code Playgroud)

请注意对Interface() 的调用。

游乐场链接

&User在我看来,当你已经有一个时,你会很麻烦地做一个空的b,例如

func Get(a []byte, b interface{}) {
    MustJSONDecode(a, &b)
    fmt.Printf("obj = %#v\n", b)
}
Run Code Online (Sandbox Code Playgroud)

但我猜这个计划还有一些在这里不明显的内容!