package mainimport ( "fmt" "encoding/json" "reflect")var ( datajson []byte //ref mapp)type mapp map[string]reflect.Typetype 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)}在獲取函數(shù)中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) }我無(wú)法將 json 解組為基礎(chǔ)對(duì)象類型。這里有什么問(wèn)題?我被困在這里了。一件很簡(jiǎn)單卻又很難搞清楚的事情。謝謝更新::此問(wèn)題的目標(biāo)是檢索在 Get 函數(shù)中傳遞的類型完整的對(duì)象。Nick 在下面的評(píng)論中提到的方法并沒(méi)有讓我得到我之前已經(jīng)嘗試過(guò)的實(shí)際對(duì)象。我無(wú)論如何都可以在這樣的地圖中檢索數(shù)據(jù)(即使對(duì)象下面有遞歸對(duì)象)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)}但是我需要返回的不僅僅是數(shù)據(jù)的實(shí)際對(duì)象。就像user := &User{"SomeName"}我需要user從 Unmarshall 返回對(duì)象的地方。訣竅是在反射中的某個(gè)地方,但不知道如何。
- 2 回答
- 0 關(guān)注
- 187 瀏覽
添加回答
舉報(bào)
0/150
提交
取消