Skip to content

Commit

Permalink
Merge pull request #22 from manicar2093/fix/support-slices
Browse files Browse the repository at this point in the history
fix: add slice support
  • Loading branch information
manicar2093 authored Jan 9, 2025
2 parents 9b38034 + 7821ed7 commit b114827
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
2 changes: 1 addition & 1 deletion json.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func (c *Optional[T]) UnmarshalJSON(data []byte) error {
var (
asString = string(data)
)
if strings.Contains(asString, "\"") {
if strings.HasPrefix(asString, "\"") {
return c.stringUnmarshall(asString)
}

Expand Down
8 changes: 6 additions & 2 deletions text.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
package goption

import (
"bytes"
"fmt"
"regexp"
)

func (c *Optional[T]) UnmarshalText(text []byte) error {
does, err := regexp.Match(`^\d+(\.\d+)?$`, text)
isNumber, err := regexp.Match(`^\d+(\.\d+)?$`, text)
isArray := bytes.HasPrefix(text, []byte("["))

if err != nil {
return err
}
if does {
if isNumber || isArray {
return c.UnmarshalJSON(text)
}

return c.UnmarshalJSON([]byte(fmt.Sprintf("\"%s\"", text)))
}
36 changes: 36 additions & 0 deletions text_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,42 @@ var _ = Describe("Text", func() {
Expect(holder.Get()).To(Equal(expectedNameData))
})

It("slice type", func() {
var (
expectedNameData = `["hello", "world"]`
jsonData = []byte(expectedNameData)
holder = goption.Empty[[]string]()
)
err := holder.UnmarshalText(jsonData)

Expect(err).ToNot(HaveOccurred())
Expect(holder.Get()).To(Equal([]string{"hello", "world"}))
})

It("slices objects type", func() {
type test struct {
Name string `json:"name"`
Age int `json:"age"`
}
var (
expectedNameData = `[{"name":"hello","age":20},{"name":"hello2","age":30}]`
jsonData = []byte(expectedNameData)
holder = goption.Empty[[]test]()
)
err := holder.UnmarshalText(jsonData)

Expect(err).ToNot(HaveOccurred())
Expect(holder.Get()).To(Equal([]test{
{
Name: "hello",
Age: 20,
}, {
Name: "hello2",
Age: 30,
},
}))
})

It("empty string type", func() {
var (
expectedNameDataString = ""
Expand Down

0 comments on commit b114827

Please sign in to comment.