如何将JSON解组添加到外部库类型而不嵌入[duplicate]

问题描述 投票:-1回答:1

我做了一些搜索类似文章的工作,但是Go JSON解组是一个热门话题,在所有其他文章中我看不到任何专门针对我的问题的东西。

是否有一种为现有类型添加/注册JSON解组逻辑的方法-由外部库定义的逻辑?

示例:

import (
    "go.mongodb.org/mongo-driver/bson/primitive"
)

type SomeDBModel struct {
    Created primitive.DateTime
}

# NOTE: primitive.DateTime is an int64 and has implemented MarshalJSON,
# but not UnmarshalJSON.
# It marshals into an RFC 3339 datetime string; I'd like to be able to
# also unmarshal from RFC 3339 strings.

是否可以通过某种方式为Go的默认JSON解组器注册primitive.DateTime对象的解组函数?我宁愿不将primitive.DateTime嵌入包装器结构中。

json go unmarshalling mongo-go
1个回答
1
投票

更改类型的默认(非)编组器或添加缺少的功能的唯一方法是创建自定义类型并编写自己的方法,如下所示:

type myDateTime primitive.DateTime // custom-type

//
// re-use the MarshalJSON() that comes with `primitive.DateTime`
//
func (t myDateTime) MarshalJSON() ([]byte, error) { return primitive.DateTime(t).MarshalJSON() }

//
// fill in the missing UnmarshalJSON for your custom-type
//
func (t *myDateTime) UnmarshalJSON(b []byte) (err error) {

    var pt time.Time // use time.Time as it comes with `UnmarshalJSON`
    err = pt.UnmarshalJSON(b)
    if err != nil {
        return
    }
    *t = myDateTime(
        primitive.NewDateTimeFromTime(pt),
    )
    return
}

并在您自己的类型中使用:

type SomeDBModel struct {
    Created myDateTime // instead of `primitive.DateTime`
}

正在工作playground example

© www.soinside.com 2019 - 2024. All rights reserved.