I have an enum defined as
type MyEnum int
const(
FirstEnum MyEnum = iota
)
Then, I have a json that has the key-value pair "Key": "FirstEnum"
. I'm unmarshalling like this.
var data map[string]interface{}
err := json.Unmarshal([]byte(json), &data)
x := data["key"].(MyEnum)
When I run this, however, I get the error:
panic: interface conversion: interface {} is string, not ps.Protocol [recovered]
panic: interface conversion: interface {} is string, not ps.Protocol
Is there a way to get this to work like a normal conversion of a string representation of a enum to enum type in Go?
I figured out something that works in a similar way (at least works for my current situation):
Use string
for enum
-like constants:
type MyEnum string
const(
FirstEnum MyEnum = "FirstEnum"
)
Now, use the decoding json to custom types as mentioned here.
data := MyJsonStruct{}
err := json.Unmarshal([]byte(json), &data)
MyJsonStruct
would look something like:
type MyJsonStruct struct {
Key MyEnum
}
You can then make MyJsonStruct implement the Unmarshaler
interface, so you can validate the given values.
func (s *MyJsonStruct) UnmarshalJSON(data []byte) error {
// Define a secondary type so that we don't end up with a recursive call to json.Unmarshal
type Aux MyJsonStruct;
var a *Aux = (*Aux)(s);
err := json.Unmarshal(data, &a)
if err != nil {
return err
}
// Validate the valid enum values
switch s.Key {
case FirstEnum, SecondEnum:
return nil
default:
s.Key = ""
return errors.New("invalid value for Key")
}
}