Skip to content

Commit

Permalink
Handle null in UnmarshalJSON()
Browse files Browse the repository at this point in the history
  • Loading branch information
Norman Gehrsitz committed Nov 7, 2023
1 parent ccd7616 commit 45eb78e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
7 changes: 7 additions & 0 deletions uniqueidentifier_null.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ func (n NullUniqueIdentifier) MarshalText() (text []byte, err error) {

func (n *NullUniqueIdentifier) UnmarshalJSON(b []byte) error {
u := n.UUID
if string(b) == "null" {
*n = NullUniqueIdentifier{
UUID: [16]byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
Valid: false,
}
return nil
}
err := u.UnmarshalJSON(b)
*n = NullUniqueIdentifier{
UUID: u,
Expand Down
20 changes: 20 additions & 0 deletions uniqueidentifier_null_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,26 @@ func TestNullableUniqueIdentifierUnmarshalJSON(t *testing.T) {
}
}

func TestNullableUniqueIdentifierUnmarshalJSONNull(t *testing.T) {
t.Parallel()
u := NullUniqueIdentifier{
UUID: [16]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
Valid: true,
}

err := u.UnmarshalJSON([]byte("null"))
if err != nil {
t.Fatal(err)
}
expected := NullUniqueIdentifier{
UUID: [16]byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
Valid: false,
}
if u != expected {
t.Errorf("u.UnmarshalJSON() = %v; want %v", u, expected)
}
}

var _ fmt.Stringer = NullUniqueIdentifier{}
var _ sql.Scanner = &NullUniqueIdentifier{}
var _ driver.Valuer = NullUniqueIdentifier{}

0 comments on commit 45eb78e

Please sign in to comment.