Golang - 具有零/空值的指针上的客户解组器/编组器我正在尝试实现自定义UnmarshalJSON和MarshalJSON指针类型,但是当来自 json 的数据null/nil如下例所示时,不会调用此函数:package mainimport ( "encoding/json" "fmt")type A struct { B *B `json:"b,omitempty"`}type B int// Only for displaying value instead of// pointer address when calling `fmt.Println`func (b *B) String() string { if b == nil { return "nil" } return fmt.Sprintf("%d", *b)}// This function is not triggered when json// data contains null instead of number valuefunc (b *B) UnmarshalJSON(data []byte) error { fmt.Println("UnmarshalJSON on B called") var value int if err := json.Unmarshal(data, &value); err != nil { return err } if value == 7 { *b = B(3) } return nil}// This function is not triggered when `B`// is pointer type and has `nil` valuefunc (b *B) MarshalJSON() ([]byte, error) { fmt.Println("MarshalJSON on B called") if b == nil { return json.Marshal(0) } if *b == 3 { return json.Marshal(7) } return json.Marshal(*b)}func main() { var a A // this won't call `UnmarshalJSON` json.Unmarshal([]byte(`{ "b": null }`), &a) fmt.Printf("a: %+v\n", a) // this won't call `MarshalJSON` b, _ := json.Marshal(a) fmt.Printf("b: %s\n\n", string(b)) // this would call `UnmarshalJSON` json.Unmarshal([]byte(`{ "b": 7 }`), &a) fmt.Printf("a: %+v\n", a) // this would call `MarshalJSON` b, _ = json.Marshal(a) fmt.Printf("b: %s\n\n", string(b))}输出:a: {B:nil}b: {}UnmarshalJSON on B calleda: {B:3}MarshalJSON on B calledb: {"b":7}我的问题是:为什么UnmarshalJSON/MarshalJSON不使用null/nil指针类型的值调用我们如何UnmarshalJSON/MarshalJSON每次调用数据null/nil和类型是指针而不是UnmarshalJSON/MarshalJSON在A类型上实现并b从级别修改属性A
1 回答
梦里花落0921
TA贡献1772条经验 获得超6个赞
简称
目前,解组/编组 Go 结构将仅发出非零字段,因为在 Go 中nil pointer
是一个零值,在这种情况下不会调用。UnmarshalJSON/MarshalJSON
另外,似乎有一些相关的建议
但是,现在没有办法解决。
每个代码 解组器
Unmarshalers 将 UnmarshalJSON([]byte("null")) 实现为空操作
// By convention, to approximate the behavior of Unmarshal itself,
// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
type Unmarshaler interface {
UnmarshalJSON([]byte) error
}
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报
0/150
提交
取消