这个问题在这里已经有了答案:
Custom JSON marshaling for external packages
(1 个回答)
2年前关闭。
我搜索了一些类似的帖子,但是 Go JSON unmarshalling 是一个热门话题,在所有其他帖子中我看不到任何专门针对我的问题的内容。
有没有办法为现有类型添加/注册 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.
有什么方法可以为
primitive.DateTime
注册解码功能吗? Go 的默认 JSON 解码器的对象?我宁愿不嵌入 primitive.DateTime
进入包装结构。
最佳答案
更改类型的默认(取消)编码器 - 或添加缺少的功能 - 的唯一方法是创建自定义类型并编写自己的方法,如下所示:
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
关于json - 如何在不嵌入的情况下将 JSON 解码添加到外部库类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60841763/