Handling Custom BSON Marshaling

前端 未结 1 1645
清歌不尽
清歌不尽 2020-12-15 23:05

I have a number of structs that require custom marshalling. When I was testing I was using JSON and the standard JSON marshaller. As it doesn\'t marshal unexported fields, I

相关标签:
1条回答
  • 2020-12-15 23:49

    Custom bson Marshalling/Unmarshalling works nearly the same way, you have to implement the Getter and Setter interfaces respectively

    Something like this should work :

    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 struct {
            Value        float64 `json:"value" bson:"value"`
            CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`
        }{
            Value:        f,
            CurrencyCode: c.currencyCode,
        }, nil
    }
    
    // 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"`
        })
    
        bsonErr := raw.Unmarshal(decoded)
    
        if bsonErr == nil {
            c.value = decimal.NewFromFloat(decoded.Value)
            c.currencyCode = decoded.CurrencyCode
            return nil
        } else {
            return bsonErr
        }
    }
    
    0 讨论(0)
提交回复
热议问题