gpt4 book ai didi

go - 将 json.RawMessage 解码为反射 slice

转载 作者:IT王子 更新时间:2023-10-29 01:39:54 29 4
gpt4 key购买 nike

在下面的示例中,我尝试使用反射将 Unmarshal 一个 json.RawMessage 放入一个 slice 中,以确定 json 中的项目类型.RawMessagejson.RawMessage 始终表示特定类型的数组,类型的名称包含在 json 中,指向它的指针从 map 中检索[字符串]接口(interface){}

 type command struct {
Action *string
Type *string
Items json.RawMessage //because i need to figure out the Type field value first, its always an array of a single type
}

//a sample model
type Chicken struct {
Id *int
Name *string
EggColor *string
}

//this map contains a pointer to each needed struct using reflection i can get the type and make a SliceOf it
var ModelRegistery map[string]interface {}

func main(){

//register the Chicken type to retrieve a pointer to it using a string key
var chickenPtr *Chicken
ModelRegistery = make(map[string]interface {})
ModelRegistery["Chicken"] = chickenPtr

//some json for testing
cJson := []byte(`{"Action":"BURN",
"Type":"Chicken",
"Items":[{"Id":1,"Name":"B","EggColor":"D"},
{"Id":2,"Name":"M","EggColor":"C"}]}`)


var command command
err := json.Unmarshal(cJson,&command)
if err != nil {
log.Fatalln("error:", err)
}

//get the type from the model registry and reflect it
itemtyp := reflect.TypeOf(ModelRegistery[(*command.Type)]).Elem()
//create a slice of the type
itemslice := reflect.SliceOf(itemtyp)
rv := reflect.MakeSlice(itemslice, 0, 2)

//now when trying to unmarshal the json.RawMessage field i get an exception
err = json.Unmarshal(command.Items,&rv)
if err != nil {
log.Fatalln("error:", err) //error: json: cannot unmarshal array into Go value of type reflect.Value
}
}

问题是,我在最后一部分做错了什么?为什么我得到异常?

json: cannot unmarshal array into Go value of type reflect.Value

这是一个goplay http://play.golang.org/p/63dxgnPFz_

最佳答案

您需要将 interface{} 传递给解码函数,而不是 reflect.Value。

更改以下内容似乎有效:

itemslice := reflect.SliceOf(itemtyp)
rv := reflect.New(itemslice)

//now when trying to unmarshal the json.RawMessage field i get an exception
err = json.Unmarshal(command.Items, rv.Interface())

关于go - 将 json.RawMessage 解码为反射 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25033662/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com