在我上次question时,我想将eunm(类型别名)转换为字符串,当我用mgo将其写入mongodb时。我知道我需要为bson Marshal / Unmarshal添加规则,但它与json有所不同,我需要实现UnmarshalJSON
和MarshalJSON
,那么我应该如何处理bson?下面的代码将一个数字写入字段S
,但我想要相应的字符串
package main
import (
"encoding/json"
mgo "gopkg.in/mgo.v2"
)
type trxStatus int
type test struct {
S trxStatus
A string
}
const (
buySubmitted trxStatus = iota
buyFilled
sellSubmiited
sellFilled
finished
)
var ss = [...]string{"buySubmitted", "buyFilled", "sellSubmiited", "sellFilled", "Finished"}
// that's what I do for json
func (s *trxStatus) UnmarshalJSON(bytes []byte) error {
var status string
json.Unmarshal(bytes, &status)
// unknown
for i, v := range ss {
if v == status {
tttt := trxStatus(i)
*s = tttt
break
}
}
return nil
}
func (s trxStatus) MarshalJSON() ([]byte, error) {
return json.Marshal(s.String())
}
func (s trxStatus) String() string {
if s < buySubmitted || s > finished {
return "Unknown"
}
return ss[s]
}
func main() {
db, _ := mgo.Dial("localhost")
s := test{S: buyFilled, A: "hello"}
c := db.DB("test").C("test")
c.Insert(s)
}