2021-07-03 15:31:42 +08:00
|
|
|
package carbon
|
|
|
|
|
|
|
|
import (
|
2021-07-19 09:53:30 +08:00
|
|
|
"bytes"
|
2021-07-03 15:31:42 +08:00
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2024-02-01 11:24:43 +08:00
|
|
|
// MarshalJSON implements the json.Marshaler interface.
|
|
|
|
// 实现 json.Marshaler 接口
|
2023-12-22 16:09:01 +08:00
|
|
|
func (c Carbon) MarshalJSON() ([]byte, error) {
|
|
|
|
if c.Error != nil {
|
|
|
|
return nil, c.Error
|
2021-08-16 09:45:48 +08:00
|
|
|
}
|
2023-12-26 21:49:48 +08:00
|
|
|
key, value, tz := c.parseTag()
|
2024-01-02 23:28:38 +08:00
|
|
|
data := ""
|
2023-12-22 16:09:01 +08:00
|
|
|
if key == "layout" {
|
2023-12-26 21:49:48 +08:00
|
|
|
data = fmt.Sprintf(`"%s"`, c.Layout(value, tz))
|
2022-05-07 09:19:57 +08:00
|
|
|
}
|
2023-12-22 16:09:01 +08:00
|
|
|
if key == "format" {
|
2024-01-02 23:28:38 +08:00
|
|
|
// timestamp without double quotes in json
|
|
|
|
if value == "U" || value == "V" || value == "X" || value == "Z" {
|
|
|
|
data = fmt.Sprintf(`%s`, c.Format(value, tz))
|
|
|
|
} else {
|
|
|
|
data = fmt.Sprintf(`"%s"`, c.Format(value, tz))
|
|
|
|
}
|
2022-05-07 09:19:57 +08:00
|
|
|
}
|
2023-12-26 21:49:48 +08:00
|
|
|
return []byte(data), nil
|
2022-05-07 09:19:57 +08:00
|
|
|
}
|
|
|
|
|
2024-02-01 11:24:43 +08:00
|
|
|
// UnmarshalJSON implements the json.Unmarshaler interface.
|
|
|
|
// 实现 json.Unmarshaler 接口
|
2023-12-22 16:09:01 +08:00
|
|
|
func (c *Carbon) UnmarshalJSON(b []byte) error {
|
|
|
|
if c.Error != nil {
|
|
|
|
return c.Error
|
2022-05-07 09:19:57 +08:00
|
|
|
}
|
2023-12-26 21:49:48 +08:00
|
|
|
key, value, tz := c.parseTag()
|
|
|
|
data := fmt.Sprintf("%s", bytes.Trim(b, `"`))
|
2023-12-22 16:09:01 +08:00
|
|
|
if key == "layout" {
|
2023-12-26 21:49:48 +08:00
|
|
|
*c = ParseByLayout(data, value, tz)
|
2021-08-16 09:45:48 +08:00
|
|
|
}
|
2023-12-22 16:09:01 +08:00
|
|
|
if key == "format" {
|
2023-12-26 21:49:48 +08:00
|
|
|
*c = ParseByFormat(data, value, tz)
|
2024-01-02 23:28:38 +08:00
|
|
|
}
|
2024-01-07 20:07:35 +08:00
|
|
|
c.tag = &tag{
|
2024-01-02 23:28:38 +08:00
|
|
|
carbon: fmt.Sprintf("%s:%s", key, value),
|
|
|
|
tz: tz,
|
2022-04-12 23:23:19 +08:00
|
|
|
}
|
2022-11-04 10:47:29 +08:00
|
|
|
return c.Error
|
2022-04-12 23:23:19 +08:00
|
|
|
}
|