gpt4 book ai didi

go - 从 io.Reader 在 golang 中解码 json 中的枚举

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:06 25 4
gpt4 key购买 nike

我在 json 中有一个字段是 abcdef 我想确保当我解码数据时它会检查该字段是否只包含其中一个2 个有效值,有没有办法在 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

最佳答案

根据doc ,这里是 UnmarshalJson 的签名。所以 UnmarshalJson 的参数只能是 []byte

类型

如果输入是io.Reader,你可以使用NewDecoderDecode .然后可以将结果传递给 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")
}
}

关于go - 从 io.Reader 在 golang 中解码 json 中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57489797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com