我有一个包含math/big.Int字段的结构.我想使用mgo在mongodb中保存结构.在我的情况下,将数字保存为字符串就足够了.
我查看了可用字段的标签,没有任何接缝以允许自定义序列化程序.我期望实现类似的接口,encoding/json.Marshaler但我在文档中找不到这样的接口.
这是我想要的一个简单的例子.
package main
import (
"labix.org/v2/mgo"
"math/big"
)
type Point struct {
X, Y *big.Int
}
func main() {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
c := session.DB("test").C("test")
err = c.Insert(&Point{big.NewInt(1), big.NewInt(1)})
if err != nil { // should not panic
panic(err)
}
// The code run as expected but the fields X and Y are empty in mongo
}
Run Code Online (Sandbox Code Playgroud)
Thnaks!
类似的界面名为bson.Getter:
它看起来类似于:
func (point *Point) GetBSON() (interface{}, error) {
return bson.D{{"x", point.X.String()}, {"y", point.Y.String()}}, nil
}
Run Code Online (Sandbox Code Playgroud)
如果您有兴趣,还有setter方面的对应接口:
要使用它,请注意bson.Raw作为参数提供的类型有一个Unmarshal方法,因此您可以使用类似于的类型:
type dbPoint struct {
X string
Y string
}
Run Code Online (Sandbox Code Playgroud)
并且方便地解组它:
var dbp dbPoint
err := raw.Unmarshal(&dbp)
Run Code Online (Sandbox Code Playgroud)
然后使用dbp.X和dbp.Y字符串将大的int重新放回到真正(point *Point)的unmarshalled中.
| 归档时间: |
|
| 查看次数: |
769 次 |
| 最近记录: |