douhuang5623 2014-07-30 09:46
浏览 46
已采纳

将json.RawMessage解组到反射的切片

In the following sample, i am trying to Unmarshal a json.RawMessage into a slice using reflection to figure out the type of the items in the json.RawMessage, the json.RawMessage always represents an array of a specific type, the name of the type is included in the json and a pointer to it is retrieved from a map[string]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
        }
    }

the question is, what am i doing wrong in the last part? why do i get the exception?

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

here is a goplay http://play.golang.org/p/63dxgnPFz_

  • 写回答

1条回答 默认 最新

  • duanhan5388 2014-07-30 10:03
    关注

    You need to pass interface{} to the unmarhsal function, not a reflect.Value.

    Changing the following seems to work:

    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())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况