码迷,mamicode.com
首页 > 其他好文 > 详细

4.12 序列化

时间:2018-03-22 01:40:33      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:poc   location   print   coding   UNC   odi   sprint   rom   enc   


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 序列化

标签:poc   location   print   coding   UNC   odi   sprint   rom   enc   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!