doulu4203 2016-11-06 19:02
浏览 312
已采纳

如何在Golang中解组reflect.Value

I got this test

func (t *DeviceTests) CreatePublicDevice() {
    registerRegularDevice := tester.TableTest{
        Method:      "POST",
        Path:        "/iot/devices",
        Status:      http.StatusOK,
        Name:        "CreatePublicDevice",
        Description: "register Regular Device has to return 200",
        Body:        PublicDevice,
    }
    resp := registerRegularDevice.DoubleSpin(t.Test)
    log.Println(resp.(types.Device).ID)

}

I want to keep this in a separate package so I can reuse on diferent projects.

func (test TableTest) DoubleSpin(t *testing.T) interface{} {
    actualBody := test.innnerSpin(t)
    log.Print(string(actualBody))
    thetype := reflect.TypeOf(test.Body)
    log.Println(thetype)
    receivedev := reflect.Zero(thetype)
    err := json.Unmarshal(actualBody, receivedev.Interface())
    assert.NoError(t, err)
    log.Println(receivedev)
    return receivedev.Interface()
}

Logs say:

2016/11/06 16:54:01 {"id":"581f7c49b2c79a543c627474","hostname":"Shriekersolar","alias":"my PublicDevice","channels":8,"owner":"public","location":{}}
2016/11/06 16:54:01 types.Device
2016/11/06 16:54:01 {ObjectIdHex("")   0  map[]}
2016/11/06 16:54:01 ObjectIdHex("")

Where a device looks like:

type Device struct {
    ID       bson.ObjectId     `json:"id" bson:"_id,omitempty"`
    Hostname string            `json:"hostname"`
    Alias    string            `json:"alias"`
    Channels int               `json:"channels"`
    Owner    string            `json:"owner"`
    Location map[string]string `json:"location"`
}
  • 写回答

1条回答 默认 最新

  • dqzd92796 2016-11-06 20:30
    关注

    Use reflect.New rather than reflect.Zero to get a pointer:

    thetype := reflect.TypeOf(i)
    receivedev := reflect.New(thetype)
    err := json.Unmarshal(actualBody, receivedev.Interface())
    if err != nil {
        panic(err)
    }
    

    Playground: https://play.golang.org/p/pGXRWpBFiF.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题
  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信