首页 > 其他 > 详细

4.12 序列化

时间:2018-03-22 01:09:42      阅读:218      评论:0      收藏:0      [点我收藏+]

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

func main() {

    eur, err := time.LoadLocation("Europe/Vienna")
    if err != nil {
        panic(err)
    }
    t := time.Date(2017, 11, 20, 11, 20, 10, 0, eur)

    // json.Marshaler interface
    b, err := t.MarshalJSON()
    if err != nil {
        panic(err)
    }
    fmt.Println("Serialized as RFC 3339:", string(b))
    t2 := time.Time{}
    t2.UnmarshalJSON(b)
    fmt.Println("Deserialized from RFC 3339:", t2)

    // Serialize as epoch
    epoch := t.Unix()
    fmt.Println("Serialized as Epoch:", epoch)

    // Deserialize epoch
    jsonStr := fmt.Sprintf("{ \"created\":%d }", epoch)
    data := struct {
        Created int64 `json:"created"`
    }{}
    json.Unmarshal([]byte(jsonStr), &data)
    deserialized := time.Unix(data.Created, 0)
    fmt.Println("Deserialized from Epoch:", deserialized)

}

/*

Serialized as RFC 3339: "2017-11-20T11:20:10+01:00"
Deserialized from RFC 3339: 2017-11-20 11:20:10 +0100 +0100
Serialized as Epoch: 1511173210
Deserialized from Epoch: 2017-11-20 18:20:10 +0800 CST
*/

4.12 序列化

原文:https://www.cnblogs.com/zrdpy/p/8620898.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!