随时间变化的JSON时空.时间字段 [英] JSON omitempty With time.Time Field

查看:66
本文介绍了随时间变化的JSON时空.时间字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试对包含2个时间字段的结构进行元数据编组.但是我只希望该字段具有时间值才能通过.所以我正在使用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

实际结果:

{"Timestamp":"2015-09-18T00:00:00Z","Date":"0001-01-01T00:00:00Z"}

{"Timestamp":"2015-09-18T00:00:00Z","Date":"0001-01-01T00:00:00Z"}

所需结果:

Desired Outcome:

{时间戳记":"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,它将起作用(对于json封送/拆组,nil指针被视为空").因此,在这种情况下,无需编写自定义 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"}

去游乐场上尝试.

如果您不能或不想将其更改为指针,则仍可以通过实现自定义 Unmarshaler .如果这样做,则可以使用 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时空.时间字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆