carbon/encoding.go

50 lines
1.1 KiB
Go
Raw Normal View History

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
}
2023-12-26 21:49:48 +08:00
key, value, tz := c.parseTag()
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))
}
2023-12-22 16:09:01 +08:00
if key == "format" {
// 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))
}
}
2023-12-26 21:49:48 +08:00
return []byte(data), nil
}
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
}
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)
}
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-07 20:07:35 +08:00
c.tag = &tag{
carbon: fmt.Sprintf("%s:%s", key, value),
tz: tz,
}
2022-11-04 10:47:29 +08:00
return c.Error
}