亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何只允許“省略” Unmarshal() 而不是 Marshal()?

如何只允許“省略” Unmarshal() 而不是 Marshal()?

Go
三國紛爭 2022-10-17 09:50:11
我有一個結構:type MyStruct struct {  a string `json:"a,omitempty"`  b int `json:"b"`  c float64 `json:"c,omitempty"`}做時如何使字段a和c可選json.Unmarshal(...),但始終出現在輸出 json 中 - 做時json.Marshal(...)?
查看完整描述

1 回答

?
慕桂英4014372

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}


查看完整回答
反對 回復 2022-10-17
  • 1 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號