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