小编ley*_*ski的帖子

处理自定义BSON Marshaling

我有许多需要自定义编组的结构.当我测试时,我使用的是JSON和标准的JSON marshaller.因为它没有编组未导出的字段,所以我需要编写一个自定义的MarshalJSON函数,它完美地工作.当我在包含需要自定义编组作为字段的父结构上调用json.Marshal时,它工作正常.

现在我需要为BSO的一些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 …
Run Code Online (Sandbox Code Playgroud)

json go mongodb bson

11
推荐指数
1
解决办法
1万
查看次数

如何将以下划线开头的字段编组为 JSON [Golang]

Go 的encoding/json包具有一些出色的 JSON 编组功能,并且出于所有意图和目的,这正是我所需要的。但是当我想尝试编组我想插入到 MongoDB 实例中的东西时,问题就出现了。

MongoDB 理解 _id为索引标识符,但 Go 的 JSON 包仅编组导出的字段,因此 MongoDB 在我保存时为文档创建自己的 ID,这是我不想要的,我什至还没有开始测试它对解组的影响一个结构。

有没有办法让 JSON 编组器包含以下划线开头的字段,而无需编写全新的字段?

json go mongodb

2
推荐指数
1
解决办法
1776
查看次数

标签 统计

go ×2

json ×2

mongodb ×2

bson ×1