The encoding/json Unmarshaler
interface will work with the Operator
type, but it must have a pointer as its receiver:
func (o *Operator) UnmarshalJSON(b []byte) error {
str := strings.Trim(string(b), `"`)
switch {
case str == "CONTAINS":
*o = CONTAINS
default:
*o = UNKNOWN
// or return an error...
}
return nil
}
The JSON decoder will take the address of the Operator
field from the Filter
struct and invoke the UnmarshalJSON
method on it.
Note that you could implement the more generic encoding/TextUnmarshaler
instead, by changing UnmarshalJSON
to UnmarshalText
above.
Here is a playground example: http://play.golang.org/p/szcnC6L86u
Arguably it might be simpler to use a string base type for Operator instead: http://play.golang.org/p/FCCg1NOeYw