【问题标题】:How to allow "omitempty" only Unmarshal() and not when Marshal()?如何只允许“省略” Unmarshal() 而不是 Marshal()?
【发布时间】:2021-12-29 15:59:51
【问题描述】:

我有一个结构:

type MyStruct struct {
  a string `json:"a,omitempty"`
  b int `json:"b"`
  c float64 `json:"c,omitempty"`
}

在执行json.Unmarshal(...) 时如何使字段ac 可选,但在执行json.Marshal(...) 时始终出现在输出json 中?

【问题讨论】:

  • Unmarshal 不看omitempty。所以你可以删除omitempty 来做你想做的事。

标签: json go


【解决方案1】:

解组 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}

【讨论】:

    猜你喜欢
    • 2010-11-02
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多