我想省略嵌套在 JSON 請求中的某些結構。我在 golang 上創建了一個 rest API,它從 http 請求中讀取消息正文,將其解碼為代碼中定義的結構并將其插入 Mongo DB我的結構如下。請注意,對于嵌套結構C,我使用了一個指針以便能夠省略它。type A struct { Title string `json:"title"` Text string `json:"text"` Data B `json:"data"`}type B struct { Product *C `json:"product,omitempty"` ExternalLink string `json:"external_link,omitempty"`}type C struct { Name string `json:"name"` Id int `json:"id"` }這是我解碼它的方式(沒有去 Json.Unmarshall 因為我讀到對于 http 主體,解碼應該在unmarshall上使用)func NewMessage(req *http.Request) *A { var newMessage *A json.NewDecoder(req.Body).Decode(&newMessage) messageInData := newMessage return newMessage}返回時的“newMessage”直接插入到 Mongo 中。但是,即使請求有效負載不包含諸如結構 C 之類的對象,如下所示{ "title": "First message from GoLang", "text": "Hello Dastgyr", "data": { "external_link": "some link here" //no product object (C struct) here }}插入到 Mongo 中的對象仍然包含具有空值的結構 C,如下所示{ "title": "First message from GoLang", "text": "Hello Dastgyr", "data": { "product": null, "external_link": "some link here" }}我也嘗試過在 Struct A 中使用 B 作為指針,但無濟于事type A struct { Title string `json:"title"` Text string `json:"text"` Data *B `json:"data,omitempty"`}我希望能夠省略某些嵌套結構。盡管使用了指針,但我想要的結構仍然沒有遺漏。我在定義結構時犯了什么錯誤?對 golang 還是新手,所以向正確的方向推動會有所幫助
1 回答

手掌心
TA貢獻1942條經驗 獲得超3個贊
您正在使用 json 標簽進行 json 解封送處理,它似乎是正確的解封送處理(因為您沒有提到任何錯誤而得出結論,并繼續使用 MongoDB)
如何將數據添加到 MongoDB 是完全不同的事情,與您的 JSON 標記無關。它使用 bson 標簽,如果您希望使用相同的結構作為 mongo DB 模型表示,則需要添加它們。是這樣的:
type A struct {
Title string `json:"title" bson:"title"`
Text string `json:"text" bson:"text"`
Data *B `json:"data,omitempty" bson:"data,omitempty"`
}
請記住,golang 中的標簽只是一些添加了結構的元數據,一些代碼實際讀取并作用于該結構。json 庫識別并處理json:""標簽,而您可能使用的官方 go mongodb 庫將處理bson:""標簽。
- 1 回答
- 0 關注
- 95 瀏覽
添加回答
舉報
0/150
提交
取消