小编Goo*_*ong的帖子

如何在 Go 中使用自定义属性类型进行 json 解组

在我的项目中,我定义了结构,以便从 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)

json struct pointers go unmarshalling

1
推荐指数
1
解决办法
1111
查看次数

标签 统计

go ×1

json ×1

pointers ×1

struct ×1

unmarshalling ×1