在我的项目中,我定义了结构,以便从 JSON 获取数据。我尝试使用json.Unmarshal()函数。但它不适用于自定义类型属性。
有一个这样的结构:
type TestModel struct {
ID NullInt `json:"id"`
Name string `json:"name"`
}
Run Code Online (Sandbox Code Playgroud)
在那里,NullInt类型是用MarshalJSON()和UnmarshalJSON()函数的实现定义的:
// NullInt ...
type NullInt struct {
Int int
Valid bool
}
// MarshalJSON ...
func (ni NullInt) MarshalJSON() ([]byte, error) {
if !ni.Valid {
return []byte("null"), nil
}
return json.Marshal(ni.Int)
}
// UnmarshalJSON ...
func (ni NullInt) UnmarshalJSON(b []byte) error {
fmt.Println("UnmarshalJSON...")
err := json.Unmarshal(b, &ni.Int)
ni.Valid = (err == nil)
fmt.Println("NullInt:", ni)
return err …Run Code Online (Sandbox Code Playgroud)