簡體   English   中英

在golang中從io.Reader解碼json中的枚舉

[英]Decode enum from json from io.Reader in golang

我在 json 中有一個字段是abcdef ,我想確保當我解組數據時它會檢查該字段是否只包含兩個有效值中的一個,有沒有辦法在 golang 中做到這一點而無需臨時檢查?

我知道如果我有字節的 json 我可以做到

const(
   Enum1 = "abc"
   Enum1 = "def"
)

func (s *MyJsonStruct) UnmarshalJSON(data []byte) error {
    type Aux MyJsonStruct;
    var a *Aux = (*Aux)(s);
    err := json.Unmarshal(data, &a)
    if err != nil {
        return err
    }

    if s.Key != Enum1 && s.Key != Enum2 {
        s.Key = ""
        return errors.New("invalid value for Key")
    }
}

如果輸入是io.Reader如何覆蓋UnmarshalJSON

根據 文檔,這里是 UnmarshalJson 的簽名。 所以 UnmarshalJson 的參數只能是[]byte類型

如果輸入是io.Reader ,則可以使用NewDecoderDecode 然后可以將結果傳遞給 UnmarshalJSON。

另一種選擇是創建另一種方法,在UnmarshalJson調用UnmarshalJson

func (s *MyJsonStruct) myUnmarshalJSON(r io.Reader) error {
        type Aux MyJsonStruct;
        var a *Aux = (*Aux)(s);

        d := json.NewDecoder(r)
        d.Decode(&a)
        b := json.Marshal(a)
        s.UnmarshalJson(b)
}

func (s *MyJsonStruct) UnmarshalJSON([]byte) error {

    type Aux MyJsonStruct;
    var a *Aux = (*Aux)(s);

    d := json.NewDecoder(r)
    d.Decode(&a)


    if s.Key != Enum1 && s.Key != Enum2 {
        s.Key = ""
        return errors.New("invalid value for Key")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM