如何将空字符串解组为 nil

How to unmarshal emtpy string as nil

如果我有这样的 JSON 数据:

{
  nullableID: ""
}

我怎样才能解组这个结构:

help := struct {
  ID *primitive.ObjectID `json:"nullableID",omitempty`
}{}

解码成 help 这样 help.ID == nil

ObjectID 实现 Unmarshaler 接口并检查空字符串:

func (o *ObjectID) UnmarshalJSON(data []byte) error {
  if err := json.Unmarshal(data, o); err != nil {
    return err
  }
  if string(*o) == "" {
    o = nil
  }
  return nil
}

如果 ObjectID 类型是从另一个包导入的,您可以创建一个包装该类型的新类型:

// objID is a copy of primitive.ObjectID but with it's own json unmarshalling.
type objID struct {
  *primitive.ObjectID
}

func (o *objID) UnmarshalJSON(data []byte) error {
  // Same implementation as above
}

This article 解释得更详细。