在使用 Go语言 开发Web应用或API时,经常需要处理JSON数据。其中,时间字段 是一个常见但容易出错的部分。默认情况下,Go的 encoding/json 包使用 RFC3339 格式(如 2006-01-02T15:04:05Z07:00)来序列化和反序列化时间。但在实际项目中,后端可能需要接收或返回其他格式的时间字符串,比如 2024-05-01 12:30:45 或 01/05/2024。这时就需要我们进行 自定义时间解析。
假设你正在对接一个第三方API,它返回的时间格式是 "2024-05-01 12:30:45",而Go默认只识别RFC3339格式。如果你直接用 time.Time 字段去解析,会得到如下错误:
json: cannot unmarshal string into Go struct field User.CreatedAt of type time.Time 因此,掌握 Go语言 JSON处理 中的自定义时间解析技巧,是每个Go开发者必备的能力。
Go允许我们为自定义类型实现 UnmarshalJSON 和 MarshalJSON 方法,从而控制JSON的解析与生成过程。
首先,我们基于 time.Time 创建一个新的类型,比如叫 CustomTime:
package mainimport ( "time")// CustomTime 自定义时间类型,用于支持特定格式的JSON时间type CustomTime struct { time.Time} 当从JSON反序列化时,我们需要将字符串按指定格式解析为时间:
import ( "encoding/json" "fmt" "time")const timeFormat = "2006-01-02 15:04:05"func (ct *CustomTime) UnmarshalJSON(b []byte) error { // 去掉首尾引号 s := string(b[1 : len(b)-1]) if s == "" || s == "null" { return nil } t, err := time.Parse(timeFormat, s) if err != nil { return fmt.Errorf("无法解析时间 '%s': %v", s, err) } ct.Time = t return nil} 当我们把结构体转为JSON时,也要确保时间按相同格式输出:
func (ct CustomTime) MarshalJSON() ([]byte, error) { if ct.Time.IsZero() { return []byte("null"), nil } return []byte(fmt.Sprintf(`"%s"`, ct.Time.Format(timeFormat))), nil} type User struct { Name string `json:"name"` CreatedAt CustomTime `json:"created_at"`}func main() { jsonData := `{"name": "Alice", "created_at": "2024-05-01 12:30:45"}` var user User err := json.Unmarshal([]byte(jsonData), &user) if err != nil { panic(err) } fmt.Printf("解析成功: %+v\n", user) // 再次序列化回JSON output, _ := json.Marshal(user) fmt.Printf("重新生成JSON: %s\n", output)} 运行结果:
解析成功: {Name:Alice CreatedAt:{wall:1395856456789012345 ext:63850307445 loc:Local}}重新生成JSON: {"name":"Alice","created_at":"2024-05-01 12:30:45"} 2006-01-02 15:04:05(这是Go诞生的时间)。MySQLTime、UnixTimestamp 等。通过本文,你已经学会了如何在 Go语言 中对 JSON处理 进行 自定义时间解析。这不仅解决了格式不兼容的问题,还提升了代码的健壮性和可维护性。无论你是初学者还是有经验的开发者,掌握这一技巧都能让你在处理API数据时更加得心应手。
关键词回顾:Go语言、JSON处理、自定义时间解析、时间格式化。
本文由主机测评网于2025-12-10发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025125646.html