dromara / carbon

A simple, semantic and developer-friendly golang package for time.
https://pkg.go.dev/github.com/dromara/carbon/v2
MIT License
4.83k stars 242 forks source link

cannot parse string null #225

Closed a8ss closed 8 months ago

a8ss commented 8 months ago
import ("github.com/golang-module/carbon/v2")
type Person struct {
    Field1 string        `json:"field1,omitempty"`
    Field2 carbon.Carbon `json:"field2,omitempty" carbon:"omitempty"`
}
var p Person
err := json.Unmarshal([]byte("{\"field1\":null,\"field2\":null}"), &p)
fmt.Println(err, p)

cannot parse string "null" as carbon by layout "2006-01-02 15:04:05", please make sure the value and layout match { }

Add the omitempty tag to prevent parsing errors ?

gouguoyin commented 8 months ago

{"field1":null,"field2":null} -> {"field1":"","field2":""}

a8ss commented 8 months ago

The responses of some APIs are null, and I have no control over them.

gouguoyin commented 8 months ago

Supported since v2.3.10

type Person struct {
  Birthday1 carbon.Carbon 
  Birthday2 carbon.Carbon
}
str := `{
  "birthday1":"",
  "birthday2":null
}`
var person Person
unmarshalErr := json.Unmarshal([]byte(str), &person)
fmt.Println(unmarshalErr) // nil
fmt.Println(person.Birthday1.String()) // empty string
fmt.Println(person.Birthday2.String()) // empty string