Skip to content

Commit

Permalink
Merge pull request #13 from manicar2093/fix-null-unmarshal
Browse files Browse the repository at this point in the history
fix: null unmarshal
  • Loading branch information
manicar2093 authored Jun 12, 2024
2 parents 2f1bc3b + dd79489 commit 2f59843
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 12 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@

dist/
.idea
4 changes: 2 additions & 2 deletions echo.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"fmt"
)

func (cb *Optional[T]) UnmarshalText(text []byte) error {
return cb.UnmarshalJSON([]byte(fmt.Sprintf("\"%s\"", text)))
func (c *Optional[T]) UnmarshalText(text []byte) error {
return c.UnmarshalJSON([]byte(fmt.Sprintf("\"%s\"", text)))

}
19 changes: 13 additions & 6 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,24 @@ import (
"encoding/json"
"reflect"
"strconv"
"strings"
)

func (c *Optional[T]) UnmarshalJSON(data []byte) error {
unquoted, err := strconv.Unquote(string(data))
if err != nil {
return err
var (
err error
asString = string(data)
)
if strings.HasPrefix(asString, "\"") {
asString, err = strconv.Unquote(asString)
if err != nil {
return err
}
}
if unquoted == "null" {
unquoted = ""
if asString == "null" {
asString = ""
}
c.isValidValue = getIsValidDataBool(unquoted)
c.isValidValue = getIsValidDataBool(asString)
if err := json.Unmarshal(data, &c.value); err != nil {
return err
}
Expand Down
11 changes: 7 additions & 4 deletions json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,19 @@ var _ = Describe("Json", func() {
})

When("is as null", func() {
It("creates an empty optional", func() {
DescribeTable("creates an empty optional", func(jsonData []byte) {
var (
jsonData = []byte(`"null"`)
holder = goption.Empty[string]()
holder = goption.Empty[string]()
)
err := holder.UnmarshalJSON(jsonData)

Expect(err).ToNot(HaveOccurred())
Expect(holder.IsPresent()).To(BeFalse())
})
},
Entry("null as string", []byte(`"null"`)),
Entry("native null", []byte(`null`)),
)

})

When("is zero", func() {
Expand Down

0 comments on commit 2f59843

Please sign in to comment.