If I have some JSON data like this:
{
nullableID: ""
}
How can I get unmarshalling this struct:
help := struct {
ID *primitive.ObjectID `json:"nullableID",omitempty`
}{}
To decode into help such that help.ID == nil
If I have some JSON data like this:
{
nullableID: ""
}
How can I get unmarshalling this struct:
help := struct {
ID *primitive.ObjectID `json:"nullableID",omitempty`
}{}
To decode into help such that help.ID == nil
Have ObjectID implement the Unmarshaler interface and check for an empty string:
func (o *ObjectID) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, o); err != nil {
return err
}
if string(*o) == "" {
o = nil
}
return nil
}
If the ObjectID type is imported from another package, you can create a new type that wraps that type:
// 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 explains it in a lot more detail.