dongshi3061 2019-08-14 07:13
浏览 257

从Golang中的io.Reader中的json解码枚举

I have a field in json that is either abc or def and I want to make sure that when I unmarshal the data it checks that the field only contains either of the 2 valid values, is there a way to do that in golang without adhoc checking?

I know I can do it if I have the json in byte

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")
    }
}

How to override UnmarshalJSON if the input is io.Reader

  • 写回答

1条回答 默认 最新

  • dragonhong641016 2019-08-14 08:06
    关注

    According to the doc, here is the signature of UnmarshalJson. So the argument of the UnmarshalJson can only be of type []byte

    If the input is a io.Reader, you can use NewDecoder and Decode. With that the result can then be pass to UnmarshalJSON.

    The other option would be to create another method that will call UnmarshalJson under the hood

    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")
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装