登录
首页 >  Golang >  Go问答

如何忽略结构的 MarshalJSON 实现(带有嵌套结构)?

来源:stackoverflow

时间:2024-04-14 20:18:37 453浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《如何忽略结构的 MarshalJSON 实现(带有嵌套结构)?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

是否可以忽略结构的自定义 marshaljson 实现, 并仅使用标准封送处理函数?

结构体比较复杂,有很多嵌套结构体,全部都是 使用自定义 marshaljson,我想忽略它们。

我觉得这应该是微不足道的。你有什么想法吗?

一些细节

创建新类型的明显解决方案效果不佳,因为嵌套结构仍然使用它们的 marshaljsons。

下面是代码示例:

func (de DeploymentExtended) MarshalJSON() ([]byte, error) {
    objectMap := make(map[string]interface{})
    if de.Location != nil {
        objectMap["location"] = de.Location
    }
    if de.Properties != nil {
        objectMap["properties"] = de.Properties
    }
    if de.Tags != nil {
        objectMap["tags"] = de.Tags
    }
    return json.Marshal(objectMap)
}

(来源:https://github.com/azure/azure-sdk-for-go/blob/v62.0.0/services/resources/mgmt/2020-10-01/resources/models.go#l366)

还有很多属性(例如 name 等),我希望在 json 中看到它们(对于 properties 和其他嵌套结构也是如此)。

此代码的 python 实现提供了该数据,我的软件使用它,并且我(将代码移植到 go)也希望能够从我的 go 程序导出这些数据。


正确答案


您可以通过两种方式执行此操作:

  • 自定义类型(隐藏 marshaljson 方法);或
  • 自定义封送拆收器(使用 reflect 在运行时忽略任何 marshaljson 方法)

自定义类型

例如,采用这些嵌套类型:

type y struct {
    fieldz string
}
type x struct {
    name string
    y    y
}


func (x *x) marshaljson() ([]byte, error) { return []byte(`"dont want this"`), nil }
func (y *y) marshaljson() ([]byte, error) { return []byte(`"definitely dont want this"`), nil }

需要隐藏这些类型以避免调用不需要的 marshaljson 方法:

type shadowy struct {
    fieldz string
}
type shadowx struct {
    name string
    y    shadowy
}

//
// transform original 'x' to use our shadow types
//
x2 := shadowx{
    name: x.name,
    y:    shadowy(x.y),
}

https://go.dev/play/p/vzKtb0gZZov

反思

这是一个简单的基于 reflect 的 json 封送拆收器来实现您想要的。它假设所有自定义封送拆收器都使用指针接收器 - 并取消引用指针,以便标准库的 json.marshal 将不会“看到”它们:

func MyJSONMarshal(v interface{}) (bs []byte, err error) {
    k := reflect.TypeOf(v).Kind() // ptr or not?

    if k != reflect.Ptr {
        return json.Marshal(v)
    }

    // dereference pointer
    v2 := reflect.ValueOf(v).Elem().Interface()
    return MyJSONMarshal(v2)
}

YMMV 使用此方法。

https://go.dev/play/p/v9YjYRno7RV

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

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