如何在Golang中解组反射值

huangapple go评论75阅读模式
英文:

How to unmarshal a reflect.Value in Golang

问题

我得到了这个测试

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"`
}
英文:

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

得分: 5

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

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.

英文:

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.

huangapple
  • 本文由 发表于 2016年11月7日 03:02:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/40453298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定