Golang 使用 json unmarshall 获取日期时间值

Golang get datetime value with json unmarshall

在我的代码中,一个方法监听了一个redis队列。我将 Redis 发送的数据作为以下代码示例的“有效负载”变量。 “currenttime”变量是 time.time,但 json.unmarshall 将其更改为字符串值。我怎样才能防止这种情况发生?我想从当前时间获取 time.time 数据。 “值”数据也动态变化。 “计数”、“名称”和“当前时间”变量名称每次都可以更改。我可以只看值。

type Event struct {
    ID    string      `json:"id"`
    Value interface{} `json:"value"`
}

func main() {

    payload := "{\"id\":\"61e310f79b9a4db146a8cb7d\",\"value\":{\"Value\":{\"count\":55,\"currenttime\":\"2022-02-23T00:00:00Z\",\"name\":\"numberone\"}}}"
    var event Event
    if err := json.Unmarshal([]byte(payload), &event); err != nil {
        fmt.Println(err)
    }
    fmt.Println(event)
}

如果Event.Value.Value具有pre-defined结构

使用适当的结构来为您的输入建模 JSON,您可以在其中使用 time.Time 作为 currenttime JSON 属性:

type Event struct {
    ID    string `json:"id"`
    Value struct {
        Value struct {
            Count       int       `json:"count"`
            CurrentTime time.Time `json:"currenttime"`
            Name        string    `json:"name"`
        } `json:"Value"`
    } `json:"value"`
}

像这样打印:

fmt.Println(event)
fmt.Printf("%+v\n", event)
fmt.Printf("%T %v\n", event.Value.Value.CurrentTime, event.Value.Value.CurrentTime)

输出是(在 Go Playground 上尝试):

{61e310f79b9a4db146a8cb7d {{55 2022-02-23 00:00:00 +0000 UTC numberone}}}
{ID:61e310f79b9a4db146a8cb7d Value:{Value:{Count:55 CurrentTime:2022-02-23 00:00:00 +0000 UTC Name:numberone}}}
time.Time 2022-02-23 00:00:00 +0000 UTC

如果Event.Value.Value没有pre-defined结构

如果 Event.Value.Value 的属性可以动态更改,请使用映射 (map[string]interface{}) 解组。因为这次我们不能告诉我们想要一个 time.Time 值(其他属性不保存时间值),所以时间字段将被解组为 string。因此,您必须遍历其值并尝试使用正确的布局来解析这些值。如果时间解析成功,我们就得到了我们想要的。

这是它的样子:

type Event struct {
    ID    string `json:"id"`
    Value struct {
        Value map[string]interface{} `json:"Value"`
    } `json:"value"`
}

func main() {

    payload := "{\"id\":\"61e310f79b9a4db146a8cb7d\",\"value\":{\"Value\":{\"foo\":55,\"mytime\":\"2022-02-23T00:00:00Z\",\"bar\":\"numberone\"}}}"
    var event Event
    if err := json.Unmarshal([]byte(payload), &event); err != nil {
        fmt.Println(err)
    }

    for _, v := range event.Value.Value {
        if s, ok := v.(string); ok {
            t, err := time.Parse("2006-01-02T15:04:05Z", s)
            if err == nil {
                fmt.Println("Found time:", t)
            }
        }
    }
}

这将输出(在 Go Playground 上尝试):

Found time: 2022-02-23 00:00:00 +0000 UTC