我有一個結構:
type MyStruct struct {
a string `json:"a,omitempty"`
b int `json:"b"`
c float64 `json:"c,omitempty"`
}
我如何在做時使欄位a和c可選json.Unmarshal(...),但總是出現在輸出 json 中 - 做時json.Marshal(...)?
uj5u.com熱心網友回復:
在解組 JSON 字串時,您無需擔心省略。如果 JSON 輸入中缺少該屬性,則結構成員將被設定為零值。
但是,您確實需要匯出結構的成員(使用A,而不是a)。
去游樂場:https : //play.golang.org/p/vRs9NOEBZO4
type MyStruct struct {
A string `json:"a"`
B int `json:"b"`
C float64 `json:"c"`
}
func main() {
jsonStr1 := `{"a":"a string","b":4,"c":5.33}`
jsonStr2 := `{"b":6}`
var struct1, struct2 MyStruct
json.Unmarshal([]byte(jsonStr1), &struct1)
json.Unmarshal([]byte(jsonStr2), &struct2)
marshalledStr1, _ := json.Marshal(struct1)
marshalledStr2, _ := json.Marshal(struct2)
fmt.Printf("Marshalled struct 1: %s\n", marshalledStr1)
fmt.Printf("Marshalled struct 2: %s\n", marshalledStr2)
}
您可以在輸出中看到,對于 struct2,成員 A 和 C 獲得它們的零值(空字串,0)。 omitempty結構定義中不存在,因此您將獲得 json 字串中的所有成員:
Marshalled struct 1: {"a":"a string","b":4,"c":5.33}
Marshalled struct 2: {"a":"","b":6,"c":0}
如果您想區分A空字串和A空/未定義,那么您將希望您的成員變數是 a *string,而不是 a string:
type MyStruct struct {
A *string `json:"a"`
B int `json:"b"`
C float64 `json:"c"`
}
func main() {
jsonStr1 := `{"a":"a string","b":4,"c":5.33}`
jsonStr2 := `{"b":6}`
var struct1, struct2 MyStruct
json.Unmarshal([]byte(jsonStr1), &struct1)
json.Unmarshal([]byte(jsonStr2), &struct2)
marshalledStr1, _ := json.Marshal(struct1)
marshalledStr2, _ := json.Marshal(struct2)
fmt.Printf("Marshalled struct 1: %s\n", marshalledStr1)
fmt.Printf("Marshalled struct 2: %s\n", marshalledStr2)
}
輸出現在更接近輸入:
Marshalled struct 1: {"a":"a string","b":4,"c":5.33}
Marshalled struct 2: {"a":null,"b":6,"c":0}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/362231.html
