我在使用時遇到了一些麻煩UnmarshalJSON,MarshalJSON我不確定我是否正確理解了它們,或者至少我有一個我無法發現的錯誤,并且在我 3 小時的谷歌搜索中我還沒有找到,所以就這樣吧。我有以下用戶結構type User struct { ID uuid.UUID `gorm:"primaryKey,type:string,size:36,<-:create" json:"id"` Username string `gorm:"unique" json:"username"` Password PasswordHash `gorm:"type:string" json:"password"` CreatedAt time.Time `gorm:"autoCreateTime:milli" json:"created_at"` UpdatedAt time.Time `gorm:"autoUpdateTime:milli" json:"updated_at,omitempty"` DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`}當我嘗試json.Marshal使用內置encoding/json庫中的函數將其轉換為 JSON 時,我得到以下信息:{"id":"3843298e-74d4-4dd7-8eff-007ab34a4c19","username":"root","password":{},"created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","deleted_at":null}我期待這樣的事情:{"id":"3843298e-74d4-4dd7-8eff-007ab34a4c19","username":"root","password":"$argon2id$v=19$m=4194304,t=1,p=64$Z9EFSTk26TQxx+Qv9g58gQ$4At0rvvv9trRcFZmSMXY0nISBuEt+1X8mCRAYbyXqSs","created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","deleted_at":null}
1 回答

慕碼人8056858
TA貢獻1803條經驗 獲得超6個贊
您已經MarshalJSON
定義了一個接收者*PasswordHash
,但您的值是類型PasswordHash
。將接收器更改為PasswordHash
并按預期工作:https ://go.dev/play/p/WukE_5JBEPL
- 1 回答
- 0 關注
- 96 瀏覽
添加回答
舉報
0/150
提交
取消