我將所有物件共有的一些屬性組合到一個結構中。
type Document struct {
ID string `json:"_id,omitempty"`
UpdatedAt time.Time `json:"updatedat"`
CreatedAt time.Time `json:"createdat"`
}
我還有一個地址結構,它不是檔案。
type Address struct {
AddressLine string `json:"addressline,omitempty"`
City string `json:"city,omitempty"`
Country string `json:"country,omitempty"`
CityCode int `json:"citycode,omitempty"`
}
我的客戶結構是一個檔案。它還有一個地址屬性。
type Customer struct {
Document `json:"document"`
Address Address `json:"address"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
Valid bool `json:"valid,omitempty"`
}
來自 MongoDB 的 JSON 物件如下;
[
{
"_id": "6186b4556971a9dbae117333",
"address": {
"addressline": "Foo Address",
"city": "Foo City",
"citycode": 0,
"country": "Foo Country"
},
"document": {
"createdat": "0001-01-01T03:00:00 03:00",
"updatedat": "0001-01-01T03:00:00 03:00"
},
"email": "[email protected]",
"name": "Foo Fooster",
"valid": false
}
]
我正在使用以下代碼來解組??它。
var customerEntity Entities.Customer
json.Unmarshal(customerEntityBytes, &customerEntity)
但我能得到的只是以下幾行。大多數欄位為空。
{{ 0001-01-01 00:00:00 0000 UTC 0001-01-01 00:00:00 0000 UTC} { 0} false}
由于我認為這是由于混合嵌套結構造成的,因此我創建了另一個客戶結構用于測驗目的;
import "time"
type AutoGenerated []struct {
ID string `json:"_id"`
Address struct {
Addressline string `json:"addressline"`
City string `json:"city"`
Citycode int `json:"citycode"`
Country string `json:"country"`
} `json:"address"`
Document struct {
Createdat time.Time `json:"createdat"`
Updatedat time.Time `json:"updatedat"`
} `json:"document"`
Email string `json:"email"`
Name string `json:"name"`
Valid bool `json:"valid"`
}
突然之間,整個問題都解決了,我可以在所有欄位都填滿的情況下訪問它。
總而言之,我無法解組我想要使用的客戶結構。我需要為此覆寫解組方法嗎?我還查看了覆寫示例,但代碼非常主觀。我將在基類中進行的更改將導致我更改解組方法。什么是干凈的方法?
uj5u.com熱心網友回復:
始終檢查錯誤。
err = json.Unmarshal(customerEntityBytes, &customerEntity)
if err != nil {
// json: cannot unmarshal array into Go value of type Entities.Customer
}
原因是,正如@mkopriva 指出的那樣-您的 JSON 是一個陣列-并且您正在解組為單個結構。修理:
var customerEntity []Entities.Customer // use slice to capture JSON array
err = json.Unmarshal(customerEntityBytes, &customerEntity)
if err != nil { /* ... */ }
您當然可以使用您的自定義型別,但是_id通過將其嵌套在您的Document結構中會丟失標記。要修復,請將其提升為Customer:
type Document struct {
//ID string `json:"_id,omitempty"`
UpdatedAt time.Time `json:"updatedat"`
CreatedAt time.Time `json:"createdat"`
}
type Customer struct {
ID string `json:"_id,omitempty"`
// ...
}
作業示例:https : //play.golang.org/p/EMcC0d1xOLf
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/352545.html
下一篇:預期切片但有介面
