1 回答

TA貢獻2011條經驗 獲得超2個贊
始終檢查錯誤。
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
- 1 回答
- 0 關注
- 97 瀏覽
添加回答
舉報