相关疑难解决方法(0)

Golang JSON omitempty with time.Time Field

试图让json Marshal包含2个时间字段的结构.但是如果它有时间价值,我只希望该字段能够通过.所以我正在使用,json:",omitempty"但它不起作用.

我可以将Date值设置为什么,因此json.Marshal会将其视为空(零)值,而不是将其包含在json字符串中?

游乐场:http://play.golang.org/p/QJwh7yBJlo

实际结果:

{ "时间戳": "2015-09-18T00:00:00Z", "日期": "0001-01-01T00:00:00Z"}

期望的结果:

{ "时间戳": "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))
}
Run Code Online (Sandbox Code Playgroud)

time json struct go

32
推荐指数
3
解决办法
1万
查看次数

标签 统计

go ×1

json ×1

struct ×1

time ×1