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 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试