我有一個結構
type Result struct {
Foo *string
}
我想得到一個像
{“Foo”:空}
我該如何做到這一點?
我嘗試了一些事情:方法1:
var res1 *Result
json.Unmarshal(nil, &res1)
方法2
var res1 Result
res1.Foo = nil
我得到一個 Foo 為 nil 的 res1 結構
感謝幫助!
編輯: var res1 *Result -> var res1 結果
uj5u.com熱心網友回復:
Go 中的基本型別不能為空。string
是基本型別。
為了Foo
可空,一種解決方案是使其成為字串指標。看起來像這樣:
type Result struct {
Foo *string
}
如果您不喜歡nil
,您還可以添加一個布爾欄位來解釋是否Foo
存在:
type Result struct {
Foo string
IsPresent bool // true if Foo is present. false otherwise.
}
但是您需要為此撰寫一個自定義 JSON 反序列化器。所以Foo
我會做一個指標。
在問題更改為提及 OP 已在使用后進行編輯*string
:
要從 JSON 字串轉到我的答案中上面列出{ "Foo" : null }
的Go 結構,可以使用package函式:Result
json
Unmarshal
var r Result
err := json.Unmarshal([]byte(`{ "Foo" : null }`), &r)
if err != nil { /* ... */ }
// now f contains the desired data
要將Result
結構體轉換為上述 JSON 字串,可以使用json
庫函式:Marshal
var r Result // Foo will be zero'd to nil
jsonStr, err := json.Marshal(&r)
if err != nil { /* ... */ }
// now jsonStr contains `{ "Foo" : null }`
這是在Go Playground中運行的上述兩個代碼塊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/508332.html