diff --git a/json.go b/json.go index 088bb86..aae1fa9 100644 --- a/json.go +++ b/json.go @@ -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) } diff --git a/text.go b/text.go index e934dc0..e1c4097 100644 --- a/text.go +++ b/text.go @@ -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))) } diff --git a/text_test.go b/text_test.go index a577f22..04b89e0 100644 --- a/text_test.go +++ b/text_test.go @@ -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 = ""