2015-11-11 118 views
1

我在我的項目中使用thrift,節儉將生成的代碼如下:我可以在jgo標籤中使用json標籤嗎?

type CvJdRelationInfo struct { 
    JdId   string `thrift:"jdId,1" json:"jdId"` 
    CvId   string `thrift:"cvId,2" json:"cvId"` 
    Status   int16 `thrift:"status,3" json:"status"` 
    AcceptTimestamp int64 `thrift:"acceptTimestamp,4" json:"acceptTimestamp"` 
} 

正如你看到的節儉已經產生json tags(但no bson tags),當我使用mgo保存記錄,mgo將自動轉換:

JdId -> jdid 
CvId -> cvid 
Status -> status 
AcceptTimeStamp -> accepttimestamp 

我需要的是:

type CvJdRelationInfo struct { 
    JdId   string `thrift:"jdId,1" json:"jdId" bson:"jdId"` 
    CvId   string `thrift:"cvId,2" json:"cvId" bson:"cvId"` 
    Status   int16 `thrift:"status,3" json:"status" bson:"status"` 
    AcceptTimestamp int64 `thrift:"acceptTimestamp,4" json:"acceptTimestamp" bson:"acceptTimestamp"` 
} 

爲您可以看到,bson tagsjson tags相同。我可以使用json tags作爲bson tags嗎?

回答

0

MongoDB實際上將數據存儲爲二進制JSON(bson),它與JSON不同。這有點令人困惑,因爲如果你使用mongo shell訪問數據庫,你會得到原始的JSON,但它實際上是一種轉換,它不是存儲格式。因此,在將數據存儲到數據庫時,「mgo」驅動程序序列化爲bson

此序列化忽略了導出密鑰,並通過默認爲struct字段的小寫版本來選擇適當的名稱。 (請參閱bson.Marshal go doc。)如果您指定一個bson導出密鑰,它將忽略結構字段名稱,並使用您指定的任何內容作爲導出密鑰bson

例如,

type User struct { 
    Name string 
    UserAge int `bson:"age"` 
    Phone string `json:"phoneNumber"` 
} 

將導致MongoDB中的結構如下:

{ 
    "name": "", 
    "age": 0, 
    "phone": "" 
} 

所以它看起來像你的結構字段應該處理大部分的東西給你。

,你可能看不到,直到它咬你,如果你不指定bson出口鍵,您不必爲留出空白字段做bson:",omitempty"能力的一個「疑難雜症」,或bson:",inline"爲編組嵌套(或嵌套)結構。

例如,這是你將如何處理嵌入結構:

type Employee struct { 
    User `bson:",inline"` 
    JobTitle string 
    EmployeeId string 
    Salary int 
} 

這種事情在我提供了關於bson.Marshal該鏈接指定。希望有所幫助!

相關問題