Skip to content

Commit

Permalink
Merge pull request #15 from manicar2093/fix/multiline-json-parsing
Browse files Browse the repository at this point in the history
fix: add handling multiline's strings to be unmarshal
  • Loading branch information
manicar2093 authored Jul 17, 2024
2 parents 3c04257 + 60a7239 commit 6f23076
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 15 deletions.
33 changes: 22 additions & 11 deletions json.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,39 @@ package goption

import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
)

func (c *Optional[T]) UnmarshalJSON(data []byte) error {
var (
err error
asString = string(data)
)
if strings.HasPrefix(asString, "\"") {
asString, err = strconv.Unquote(asString)
if err != nil {
return err
valuer struct {
Value string `json:"value"`
}
asJsonString = strings.ReplaceAll(
fmt.Sprintf(`{"value": %s}`, data),
"\n",
"\\n",
)
asJsonBytes = []byte(asJsonString)
)

if err := json.Unmarshal(asJsonBytes, &valuer); err != nil {
return err
}
if asString == "null" {
asString = ""

if valuer.Value == "null" {
valuer.Value = ""
}
c.isValidValue = getIsValidDataBool(asString)

c.isValidValue = getIsValidDataBool(valuer.Value)
if c.isValidValue {
if err := json.Unmarshal(data, &c.value); err != nil {
if err := json.Unmarshal(
[]byte(strconv.Quote(valuer.Value)),
&c.value,
); err != nil {
return err
}
}
Expand Down
14 changes: 10 additions & 4 deletions json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ var _ = Describe("Json", func() {

Describe("UnmarshalJSON", func() {

It("generates optional from json string", func() {
DescribeTable("generates optional from json string", func(expectedNameData string) {
var (
expectedNameData = "a name"
jsonData = []byte(fmt.Sprintf(
jsonData = []byte(fmt.Sprintf(
`"%v"`,
expectedNameData,
))
Expand All @@ -33,7 +32,14 @@ var _ = Describe("Json", func() {

Expect(err).ToNot(HaveOccurred())
Expect(holder.Get()).To(Equal(expectedNameData))
})
},
Entry("one line string", "a name"),
Entry("multiline strings", `a name
a name
a name
a name`),
)

When("is as null", func() {
DescribeTable("creates an empty optional", func(jsonData []byte) {
Expand Down

0 comments on commit 6f23076

Please sign in to comment.