php小编苹果今天来和大家分享一个有关处理部分更新时密钥不存在的问题。在进行PATCH请求时,有时会遇到密钥不存在的情况。那么我们应该如何处理呢?在本文中,将为大家详细介绍解决这一问题的方法和步骤,帮助大家更好地应对这种情况,保证系统的正常运行。让我们一起来看看吧!
问题内容
我正在想办法解决这个问题。
我有一个 user
结构,上面有一些字段。但是,当为 patch 用户调用解码 json 对象时,缺少键会导致值设置为 *nil。对应的数据库属性是 text null
类型,因此当 key 丢失时,结果将始终存储为 null。
type updateuserdto struct {
id uuid.uuid
firstname string
lastname string
imageurl *string
}
imageurl
可以为 nil,但是当该对象从客户端发送时:
{ firstName: "Jimmy" }
这会解码为 imageurl
= nil,因为 json 中不存在 imageurl
。
如何在不使用 map[string]struct{}
而不是我的 dto 检查每个字段是否存在的情况下处理部分更新?
解决方法
您可以实现自定义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://www.php.cn/link/22f791da07b0d8a2504c2537c560001c
另一种不需要自定义类型的方法是在解组 json 之前将 go 字段的值设置为当前数据库列的值。如果传入的 json 不包含匹配的字段,则 json.decoder
(由 json.unmarshal
使用)将不会“触及”目标的字段。
dto := loadUpdateUserDTOFromDB(conn)
if err := json.Unmarshal(data, dto); err != nil {
return err
}
https://www.php.cn/link/cdf49f5251e7b3eb4f009483121e9b64