解散反映价值

时间:2013-08-17 23:31:21

标签: json reflection go unmarshalling

Here is the code

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)

}

在获取功能

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

我无法将json解组为基础对象类型。

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

由于

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

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

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

但是我需要的实际对象不仅仅是数据。像user := &User{"SomeName"}这样的东西,我需要从Unmarshall回来user对象。诀窍在于反思,但不知道如何。

2 个答案:

答案 0 :(得分:4)

我很困惑你为什么要这样做,但这里是如何解决它

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

请注意对Interface()的调用。

Playground link

在我看来,如果&User已经有一个空b,那么你会遇到很多麻烦{/ 1}},例如

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

但我猜这个计划还有更多内容在这里不明显!

答案 1 :(得分:1)

reflect.New(objType)返回reflect.Value这不是您传递的界面。根据{{​​3}}的文档,它是一个只包含未导出字段的结构。 json包无法使用未导出的字段。因为它不是你传入的对象,它甚至不是json可编码/可解码的json包也会失败。

在尝试使用反射包时,您可能会发现Value文章很有用。