如何在struct中创建一个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
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么堆栈溢出发生?可以修复吗?
提前致谢.
看起来您可能正在尝试使用默认的解组器进行自定义解组,然后对数据进行后处理.但是,正如您所发现的,尝试此操作的明显方法会导致无限循环!
通常的解决方法是创建类型的别名,在该别名的实例上使用默认的解组,对数据进行后处理,然后最终转换为原始类型并分配回目标实例.请注意,您需要在指针类型上实现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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
322 次 |
| 最近记录: |