解组 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 是 null/undefined,那么您会希望您的成员变量是 *string,而不是 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}