登录
首页 >  Golang >  Go问答

解组 JSON 时的零日期

来源:stackoverflow

时间:2024-04-09 23:36:35 470浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《解组 JSON 时的零日期》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我正在尝试用时间值解组 json。我有这个 json 结构。

{
        "nick": "cub",
        "email": "[email protected]",
        "created_at": "2017-10-09",
        "subscribers": [
            {
                "email": "[email protected]",
                "created_at": "2017-11-30"
            },
            {
                "email": "[email protected]",
                "created_at": "2016-07-15"
            },
            {
                "email": "[email protected]",
                "created_at": "2017-02-16"
            },
            {
                "email": "[email protected]",
                "created_at": "2016-11-30"
            },
            {
                "email": "[email protected]",
                "created_at": "2018-07-10"
            },
            {
                "email": "[email protected]",
                "created_at": "2017-09-04"
            },
            {
                "email": "[email protected]",
                "created_at": "2018-01-03"
            },
            {
                "email": "[email protected]",
                "created_at": "2018-04-20"
            },
            {
                "email": "[email protected]",
                "created_at": "2018-02-17"
            }
        ]
    }

还有一个实现从json文件读取到struct user的函数。一切都很好,但是当我将 user 结构中的 createdat 字段设置为 time.time 类型时,我得到 json 文件中具有类型格式的每个字段的 0001-01-01 00:00:00 +0000 utc 值。

type Subscriber struct {
    Email     string    `json: "Email"`
    CreatedAt time.Time `json: "Created_at"`
}

type User struct {
    Nick        string       `json: "Nick"`
    Email       string       `json: "Email"`
    CreatedAt   string       `json: "Created_at"`
    Subscribers []Subscriber `json: "Subscribers"`
}

func main() {

    // Slice where objects from users.json will be pushed
    var jsonData []User

    // ReadJSON and push User struct to jsonData slice
    readJSON("users.json", &jsonData)

    for _, user := range jsonData {
        fmt.Println(user.Nick, user.Email, user.CreatedAt) // 0001-01-01 00:00:00 +0000 UTC
        fmt.Println(user.Subscribers)
    }

}

func readJSON(fileName string, userSlice *[]User) {
    file, err := os.Open(fileName)
    if err != nil {
        log.Fatal(err)
    }

    bytes, err := ioutil.ReadAll(file)
    if err != nil {
        log.Fatal(err)
    }

    err1 := json.Unmarshal(bytes, &userSlice)

    if err1 != nil {
        log.Fatal(err1)
    }

}

以 rfc3339 格式从 json 文件读取时间给用户的合适方法是什么?


解决方案


您可以使用实现 json.Unmarshaler 接口的自定义时间类型。

您可以从这个结构开始:

type customtime struct {
    time.time // embed time.time to allow calling of normal time.time methods
}

然后添加所需的 unmarshaljson([]byte) error 函数。它可能看起来像这样:

func (c *CustomTime) UnmarshalJSON(b []byte) error {
    if len(b) < 3 {
        // Empty string: ""
        return fmt.Errorf("Empty time value")
    }

    t, err := time.Parse("2006-01-02", string(b[1:len(b)-1])) // b[1:len(b)-1] removes the first and last character, as they are quotes
    if err != nil {
        return err
    }

    c.Time = t

    return nil
}

您可以在 Go Playground 上尝试该示例

今天关于《解组 JSON 时的零日期》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>