为什么mgo不能正确解开我的结构? [英] Why won't mgo unmarshall my struct properly?

查看:155
本文介绍了为什么mgo不能正确解开我的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前我发布了这个问题,询问编写自定义BSON编组/使用mgo在Go中解组。现在我来测试它了,我认为我遇到了更大的问题。我所有的结构都是无组织价值的。

Earlier I posted this question asking about writing custom BSON marshalling/unmarshalling in Go using mgo. Now I've come to test it I think I've hit on a bigger problem. All my structs unmarshal to nil values.

这是我的货币结构,包含bson.Getter和bson.Setter的实现:

This is my currency struct with the implementations of bson.Getter and bson.Setter:

type Currency struct {
    value        decimal.Decimal //The actual value of the currency.
    currencyCode string          //The ISO currency code.
}

/*
GetBSON implements bson.Getter.
*/
func (c Currency) GetBSON() (interface{}, error) {
    f, _ := c.Value().Float64()
    return bson.Marshal(struct {
        Value        float64 `json:"value" bson:"value"`
        CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`
    }{
        Value:        f,
        CurrencyCode: c.currencyCode,
    })
}

/*
SetBSON implements bson.Setter.
*/
func (c *Currency) SetBSON(raw bson.Raw) error {
    decoded := new(struct {
        Value        float64 `json:"value" bson:"value"`
        CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`
    })

    fmt.Println(string(raw.Data))
    bsonErr := raw.Unmarshal(decoded)

    if bsonErr == nil {
        fmt.Println("Debug: no error returned.")
        fmt.Println(decoded)
        c.value = decimal.NewFromFloat(decoded.Value)
        c.currencyCode = decoded.CurrencyCode
        return nil
    } else {
        return bsonErr
    }
}

通过查看原始数据,它可以正确编组,但解编结果结构只是空的。任何想法,我在这里错了吗?我使用了去得到gopkg.in/mgo.v2命令昨天字面,所以我希望它是最新的,像这样的错误不会出现在the最热的MongoDB驱动程序。

By looking at the raw data, it marshals correctly, but when unmarshaling the resulting struct is just empty. Any ideas where I'm going wrong here? I used the go get gopkg.in/mgo.v2command literally yesterday so I would hope it was up to date and a bug like this wouldn't be present in "the hottest MongoDB driver around".

推荐答案

GetBSON 方法应返回要编组的值,而不是编组结果产生的二进制数据。这就是为什么它的第一个结果类型是 interface {} 而不是 [] byte

The GetBSON method should return the value to be marshaled, not the binary data resulting from marshaling it. That's why its first result type is interface{} and not []byte.

这篇关于为什么mgo不能正确解开我的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆