首页 > 解决方案 > 如何在不嵌入的情况下将 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到包装结构中。

标签: jsongounmarshallingmongo-go

解决方案


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

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`
}

工作场所示例


推荐阅读