亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

處理自定義 BSON 編組

處理自定義 BSON 編組

Go
慕碼人8056858 2021-10-18 10:25:24
我有許多需要自定義編組的結構。當我進行測試時,我使用的是 JSON 和標準的 JSON 編組器。由于它不封送未導出的字段,我需要編寫一個自定義的 MarshalJSON 函數,該函數運行良好。當我在包含需要自定義編組作為字段的父結構上調用 json.Marshal 時,它工作正?!,F在我需要將所有內容編組到 BSON 以進行一些 MongoDB 工作,但我找不到任何有關如何編寫自定義 BSON 編組的文檔。誰能告訴我如何為我在下面演示的 BSON/mgo 做等效的事情?currency.go(重要部分)type Currency struct {    value        decimal.Decimal //The actual value of the currency.    currencyCode string          //The ISO currency code.}/*MarshalJSON implements json.Marshaller.*/func (c Currency) MarshalJSON() ([]byte, error) {    f, _ := c.Value().Float64()    return json.Marshal(struct {        Value        float64 `json:"value" bson:"value"`        CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`    }{        Value:        f,        CurrencyCode: c.CurrencyCode(),    })}/*UnmarshalJSON implements json.Unmarshaller.*/func (c *Currency) UnmarshalJSON(b []byte) error {    decoded := new(struct {        Value        float64 `json:"value" bson:"value"`        CurrencyCode string  `json:"currencyCode" bson:"currencyCode"`    })    jsonErr := json.Unmarshal(b, decoded)    if jsonErr == nil {        c.value = decimal.NewFromFloat(decoded.Value)        c.currencyCode = decoded.CurrencyCode        return nil    } else {        return jsonErr    }}product.go(同樣,只是相關部分)type Product struct {    Name  string    Code  string    Price currency.Currency}當我調用 json.Marshal(p) 其中 p 是產品時,它會生成我想要的輸出,而無需模式(不確定名稱),您可以在其中創建一個結構,該結構只是具有所有導出字段的克隆。在我看來,使用我使用過的內聯方法大大簡化了 API,并防止您有額外的結構使事情變得混亂。
查看完整描述

1 回答

?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

自定義 bson 編組/解組的工作方式幾乎相同,您必須分別實現Getter和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 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

    }

}


查看完整回答
反對 回復 2021-10-18
  • 1 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號