增加对包含null的json字符串的解码支持

This commit is contained in:
Peleus 2024-03-06 08:07:26 +08:00
parent 0a298130a9
commit 9ea513ad01
2 changed files with 27 additions and 2 deletions

View File

@ -33,6 +33,9 @@ func (c *Carbon) UnmarshalJSON(b []byte) error {
if c.Error != nil {
return c.Error
}
if string(b) == "null" || len(b) == 0 {
return nil
}
key, value, tz := c.parseTag()
data := fmt.Sprintf("%s", bytes.Trim(b, `"`))
if key == "layout" {

View File

@ -3,9 +3,8 @@ package carbon
import (
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"testing"
)
type Person struct {
@ -284,3 +283,26 @@ func TestError_Json(t *testing.T) {
fmt.Println("unmarshal error:", unmarshalErr.Error())
assert.NotNil(t, unmarshalErr)
}
// https://github.com/golang-module/carbon/issues/225
func TestCarbon_Issue225(t *testing.T) {
str := `{
"birthday1":"",
"birthday2":null
}`
type Person struct {
Birthday1 Carbon `json:"birthday1"`
Birthday2 Carbon `json:"birthday2"`
}
var person Person
unmarshalErr := json.Unmarshal([]byte(str), &person)
fmt.Println(unmarshalErr) // nil
assert.Nil(t, unmarshalErr)
assert.Equal(t, "", person.Birthday1.String())
assert.Equal(t, "", person.Birthday2.String())
fmt.Println(person.Birthday1.String()) // empty string
}