[英]Golang bson structs - use multiple field names for a single field in json but only one for writing to the database
我有一個這樣的結構 -
type Address struct {
AddressLine1 string `json:"addressLine1" bson:"addressLine1"`
AddressLine2 string `json:"addressLine2" bson:"addressLine2"`
Landmark string `json:"landmark" bson:"landmark"`
Zipcode string `json:"zipcode" bson:"zipcode"`
City string `json:"city" bson:"city"`
}
由於之前的版本和最新的尚未發布的版本之間存在一些兼容性問題,我想確保如果有人發布使用此結構解碼的 json 數據,他們應該能夠使用“zipcode”或“pincode” ' 作為其 json 中的字段名稱。 但是當這個值寫入我的數據庫時,字段名稱應該只是“郵政編碼”。
簡而言之,
{
"city": "Mumbai",
"zipcode": "400001"
}
或者
{
"city": "Mumbai",
"pincode": "400001"
}
都應該出現在數據庫中 -
{
"city": "Mumbai",
"zipcode": "400001"
}
我怎么允許這個?
您可以將兩個字段作為指向字符串的指針:
type Address struct {
AddressLine1 string `json:"addressLine1" bson:"addressLine1"`
AddressLine2 string `json:"addressLine2" bson:"addressLine2"`
Landmark string `json:"landmark" bson:"landmark"`
Zipcode *string `json:"zipcode,omitempty" bson:"zipcode"`
Pincode *string `json:"pincode,omitempty" bson:"zipcode"`
City string `json:"city" bson:"city"`
}
正如您可能注意到的,我們在 json 標簽中使用了omitempty ,因此如果其中一個字段不存在於 json 中,它將作為nil指針被忽略,並且它不會出現在Marshal()或Unmarshal() 之后
編輯:
在這種情況下,我們所要做的就是實現方法UnmarshalJSON([]byte) error
以滿足接口Unmarshaler ,方法json.Unmarshal()
將始終嘗試調用該方法,我們可以在 Unmarshal 結構后添加我們自己的邏輯,在這種情況下,我們想知道pincode是否已確定,如果我們將其分配給zipcode :此處的完整示例: https : //play.golang.org/p/zAOPMtCwBs
type Address struct {
AddressLine1 string `json:"addressLine1" bson:"addressLine1"`
AddressLine2 string `json:"addressLine2" bson:"addressLine2"`
Landmark string `json:"landmark" bson:"landmark"`
Zipcode *string `json:"zipcode,omitempty" bson:"zipcode"`
Pincode *string `json:"pincode,omitempty"`
City string `json:"city" bson:"city"`
}
// private alias of Address to avoid recursion in UnmarshalJSON()
type address Address
func (a *Address) UnmarshalJSON(data []byte) error {
b := address{}
if err := json.Unmarshal(data, &b); err != nil {
return nil
}
*a = Address(b) // convert the alias to address
if a.Pincode != nil && a.Zipcode == nil {
a.Zipcode = a.Pincode
a.Pincode = nil // unset pincode
}
return nil
}
請注意,場郵編有BSON標簽和郵遞區號不是,我們也有創造型地址的別名,以避免調用UnmarshalJSON遞歸
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.