go - 如何在 UnmarshalJSON 中调用 json.Unmarshal 而不会导致堆栈溢出?
问题描述
如何在结构中创建方法 UnmarshalJSON,在内部使用 json.Unmarshal 而不会导致堆栈溢出?
package xapo
type Xapo struct {}
func (x Xapo) UnmarshalJSON(data []byte) error {
err := json.Unmarshal(data, &x)
if err != nil {
return err
}
fmt.Println("done!")
return nil
}
有人能解释一下为什么会发生堆栈溢出吗?可以修复吗?
提前致谢。
解决方案
看起来您可能正在尝试通过使用默认解组器然后对数据进行后处理来进行自定义解组。但是,正如您所发现的,尝试这样做的明显方法会导致无限循环!
通常的解决方法是使用您的类型创建一个新类型,在新类型的实例上使用默认解组器,对数据进行后处理,然后最终转换为原始类型并分配回目标实例。请注意,您需要在指针类型上实现 UnmarshalJSON。
例如:
func (x *Xapo) UnmarshalJSON(data []byte) error {
// Create a new type from the target type to avoid recursion.
type Xapo2 Xapo
// Unmarshal into an instance of the new type.
var x2 Xapo2
err := json.Unmarshal(data, &x2)
if err != nil {
return err
}
// Perform post-processing here.
// TODO
// Cast the new type instance to the original type and assign.
*x = Xapo(x2)
return nil
}
推荐阅读
- javascript - Firebase: Firebase serve = 默认的 Firebase 应用已经存在
- javascript - 如何在 Javascript 中格式化时间戳以显示相关时区的正确时间
- c++ - 分配顺序产生不同的装配
- javascript - 量角器 - 如何将密钥发送到 contenteditable div?
- node.js - Express Js 无法从 React Js 检索提交的表单数据
- javascript - 如何将图像的 alt 与 Javascript 中选择框中的选定值相匹配?
- rest - Bitbucket 服务器 api 从包含斜杠的标签中检索提交数据
- amqp - 比较两个 AsyncAPI 规范
- kotlin - 如何将 @Cacheable 与 Kotlin 挂起功能一起使用
- android - 游戏如何在 Android 的后台运行?