mirror of
https://gitee.com/dromara/carbon.git
synced 2024-11-29 18:57:37 +08:00
增加对包含null的json字符串的解码支持
This commit is contained in:
parent
0a298130a9
commit
9ea513ad01
@ -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" {
|
||||
|
@ -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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user