1 回答

TA貢獻1871條經驗 獲得超13個贊
在解組 JSON 字符串時,您無需擔心 omitempty。如果 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}
- 1 回答
- 0 關注
- 93 瀏覽
添加回答
舉報