3 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊
在json 包文檔中:
指針值編碼為指向的值??罩羔樉幋a為空 JSON 對象。
所以你可以存儲(chǔ)一個(gè)指向字符串的指針,如果不是 nil,它將被編碼為一個(gè)字符串,如果 nil 將被編碼為“null”
type student struct {
FirstName *string `json:"first_name"`
MiddleName *string `json:"middle_name"`
LastName *string `json:"last_name"`
}

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
另一種方法實(shí)際上是使用 golang 的 json 庫提供的 MarhshalJSON 和 UnmarshalJSON 接口方法的解決方法。代碼如下:
type MyType string
type MyStruct struct {
A MyType `json:"my_type"`
}
func (c MyType) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
if len(string(c)) == 0 {
buf.WriteString(`null`)
} else {
buf.WriteString(`"` + string(c) + `"`) // add double quation mark as json format required
}
return buf.Bytes(), nil
}
func (c *MyType)UnmarshalJSON(in []byte) error {
str := string(in)
if str == `null` {
*c = ""
return nil
}
res := MyType(str)
if len(res) >= 2 {
res = res[1:len(res)-1] // remove the wrapped qutation
}
*c = res
return nil
}
那么當(dāng)使用 json.Marshal 時(shí),MyType 值將被編組為 null。
- 3 回答
- 0 關(guān)注
- 218 瀏覽
添加回答
舉報(bào)