【问题标题】:How to unmarshal a reflect.Value in Golang如何在 Golang 中解组 reflect.Value
【发布时间】:2017-03-20 02:17:08
【问题描述】:

我得到了这个测试

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)

}

我想将它保存在一个单独的包中,以便在不同的项目中重复使用。

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()
}

日志说:

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("")

设备的外观:

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"`
}

【问题讨论】:

  • 你必须传递一个指向解组的指针
  • err := json.Unmarshal(actualBody, &receivedev) 这也不起作用@JimB

标签: testing go reflection tdd


【解决方案1】:

使用reflect.New 而不是reflect.Zero 来获取指针:

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

游乐场:https://play.golang.org/p/pGXRWpBFiF

【讨论】:

    猜你喜欢
    • 2022-11-14
    • 2013-08-08
    • 2017-07-30
    • 2020-02-04
    • 2017-05-12
    • 2014-07-06
    • 1970-01-01
    • 2021-01-21
    • 2018-05-29
    相关资源
    最近更新 更多