慕桂英4014372
在解组 JSON 字符串时,您无需担心 omitempty。如果 JSON 输入中缺少该属性,则结构成员将设置为零值。但是,您确实需要导出结构的成员(使用A,而不是a)。去游乐场: https: //play.golang.org/p/vRs9NOEBZO4type 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}