json - 如何在不嵌入的情况下将 JSON 解组添加到外部库类型
问题描述
我搜索了一些类似的帖子,但是 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`
}
工作场所示例
推荐阅读
- java - 只读数据的 Spring Boot 存储库:@Query 注释类型不适用于此类声明
- python - 我如何检测(x,y)图形上的随机点并绘制五边形
- python - 如何将 libsvm 数据文件加载到 numpy 数组中以用于 sciki-learn 中的 kmeans 聚类?
- c# - 遍历嵌套类和变换属性,Multiple Int by 2
- odoo - float() 参数必须是字符串或数字,而不是“元组”
- postgresql - Docker 区别 postgres:12 来自 postgres:12-alpine
- html - 更改扩展行的 HTML
- mysql - MySQL / MariaDB / InnoDB:将可变宽度列移动到辅助表
- python - Numba 在从 lambda 函数调用的函数中并行化“for”(梯度评估)
- python - Mac上的Pyinstaller:如何在不先打开终端的情况下打开应用程序?