JSON omitempty with time.Time 字段 [英] JSON omitempty With time.Time Field
问题描述
尝试对包含 2 个时间字段的结构进行 json 编组.但我只希望该字段具有时间价值才能通过.所以我正在使用 json:",omitempty"
但它不起作用.
Trying to json Marshal a struct that contains 2 time fields. But I only want the field to come through if it has a time value. So I'm using json:",omitempty"
but it's not working.
我可以将 Date 值设置为什么,以便 json.Marshal 将其视为空(零)值而不将其包含在 json 字符串中?
What can I set the Date value to so json.Marshal will treat it like an empty (zero) value and not include it in the json string?
游乐场:http://play.golang.org/p/QJwh7yBJlo
实际结果:
{"时间戳":"2015-09-18T00:00:00Z","日期":"0001-01-01T00:00:00Z"}
{"Timestamp":"2015-09-18T00:00:00Z","Date":"0001-01-01T00:00:00Z"}
预期结果:
{"Timestamp":"2015-09-18T00:00:00Z"}
{"Timestamp":"2015-09-18T00:00:00Z"}
代码:
package main
import (
"encoding/json"
"fmt"
"time"
)
type MyStruct struct {
Timestamp time.Time `json:",omitempty"`
Date time.Time `json:",omitempty"`
Field string `json:",omitempty"`
}
func main() {
ms := MyStruct{
Timestamp: time.Date(2015, 9, 18, 0, 0, 0, 0, time.UTC),
Field: "",
}
bb, err := json.Marshal(ms)
if err != nil {
panic(err)
}
fmt.Println(string(bb))
}
推荐答案
omitempty
标签选项不适用于 time.Time
,因为它是一个 struct代码>.结构体有一个零"值,但这是一个结构体值,其中所有字段的值都为零.这是一个有效"值,因此不被视为空".
The omitempty
tag option does not work with time.Time
as it is a struct
. There is a "zero" value for structs, but that is a struct value where all fields have their zero values. This is a "valid" value, so it is not treated as "empty".
但是通过简单地将其更改为指针:*time.Time
,它会起作用(nil
指针被视为 json 编组/解组的空").因此,在这种情况下无需编写自定义 Marshaler
:
But by simply changing it to a pointer: *time.Time
, it will work (nil
pointers are treated as "empty" for json marshaling/unmarshaling). So no need to write custom Marshaler
in this case:
type MyStruct struct {
Timestamp *time.Time `json:",omitempty"`
Date *time.Time `json:",omitempty"`
Field string `json:",omitempty"`
}
使用:
ts := time.Date(2015, 9, 18, 0, 0, 0, 0, time.UTC)
ms := MyStruct{
Timestamp: &ts,
Field: "",
}
输出(根据需要):
{"Timestamp":"2015-09-18T00:00:00Z"}
在 Go Playground 上试试.
如果你不能或者不想把它改成一个指针,你仍然可以通过实现一个自定义的Marshaler
和 解组器
.如果这样做,您可以使用 Time.IsZero()
方法来确定 time.Time
值是否为零值.
If you can't or don't want to change it to a pointer, you can still achieve what you want by implementing a custom Marshaler
and Unmarshaler
. If you do so, you can use the Time.IsZero()
method to decide if a time.Time
value is the zero value.
这篇关于JSON omitempty with time.Time 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!