将json.RawMessage解组为反射切片

时间:2014-07-30 09:46:51

标签: go

在以下示例中,我尝试Unmarshal json.RawMessage使用反射来计算json.RawMessagejson.RawMessagemap[string]interface{}中项目的类型始终表示特定类型的数组,类型的名称包含在json中,并且从 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

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

{{1}}

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

1 个答案:

答案 0 :(得分:3)

您需要将interface{}传递给unmarhsal函数,而不是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())