您可以实现一个定制的json.Unmarshaler
来确定该字段是被完全省略、被提供但其值为null
,还是被提供了非空值.
type OptString struct {
IsValid bool
String *string
}
// If a field with this type has no corresponding field in the
// incoming JSON then this method will not be invoked and the
// IsValid flag's value will remain `false`.
func (s *OptString) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &s.String); err != nil {
return err
}
s.IsValid = true
return nil
}
type UpdateUserDTO struct {
ID uuid.UUID
FirstName string
LastName string
ImageURL OptString
}
https://go.dev/play/p/hvS5E46sgkD个
另一种不需要自定义类型的方法是将Go字段的值设置为current数据库列的值,只需before unmarshaling即JSON.如果传入的JSON不包含匹配的字段,则json.Decoder
(json.Unmarshal
使用)将不会"接触"目标的字段.
dto := loadUpdateUserDTOFromDB(conn)
if err := json.Unmarshal(data, dto); err != nil {
return err
}
https://go.dev/play/p/grJhr4P7sgQ个