Don't think there is any built-in way of mapping between iota
values and strings. There are some tools that generate code for doing the mapping.
I've been in similar situations and i've done something like this when I didn't want to depend on generators or other tools. Hope it serves as a start for something.
https://play.golang.org/p/MxPL-0FVGMt
package main
import (
"encoding/json"
"fmt"
)
type UserType uint
const (
UserTypeFree UserType = iota
UserTypePremium
)
var UserTypeToString = map[UserType]string{
UserTypeFree: "Free",
UserTypePremium: "Premium",
}
var UserTypeFromString = map[string]UserType{
"Free": UserTypeFree,
"Premium": UserTypePremium,
}
func (ut UserType) String() string {
if s, ok := UserTypeToString[ut]; ok {
return s
}
return "unknown"
}
func (ut UserType) MarshalJSON() ([]byte, error) {
if s, ok := UserTypeToString[ut]; ok {
return json.Marshal(s)
}
return nil, fmt.Errorf("unknown user type %d", ut)
}
func (ut *UserType) UnmarshalJSON(text []byte) error {
var s string
if err := json.Unmarshal(text, &s); err != nil {
return err
}
var v UserType
var ok bool
if v, ok = UserTypeFromString[s]; !ok {
return fmt.Errorf("unknown user type %s", s)
}
*ut = v
return nil
}
func main() {
var ut UserType
json.Unmarshal([]byte(`"Free"`), &ut)
fmt.Printf("%#v %v \n", ut, ut)
b, _ := json.Marshal(ut)
fmt.Printf("%v\n", string(b))
}