Is your feature request related to a problem? Please describe.
I have a custom type that functions like an enum. In memory it's a uint32, but in JSON, it's represented as its string value by way of a custom MarshalJSON method:
type MyEnumType uint32
const (
MyEnumTypeFirst = 1
MyEnumTypeSecond = 2
)
func (v MyEnumType) String() string {
switch v {
case MyEnumTypeFirst: return "First"
case MyEnumTypeSecond: return "Second"
}
return fmt.Sprintf("MyEnumType(%d)", v)
}
func (v MyEnumType) MarshalJSON() ([]byte, error) {
return []byte("\"" + v.String() + "\""), nil
}
type MyResponse struct {
MyValue MyEnumType `json:"myValue"`
}
If I try to tag MyResponse.MyValue with enums:"First,Second", I get an error like:
ParseComment error in file ... mypackage.MyResponse: myValue: enum value First can't convert to integer err: strconv.Atoi: parsing "First": invalid syntax
Describe the solution you'd like
Either:
allow manually specifying the data type of the enum with a tag. For example, enumType:"string" on an integer type.
rather than switching on the struct field type and attempting to marshal it (the current behaviour, ref), try each supported data type in turn, starting with the most likely type and falling back to string if no more specific type exists.
Describe alternatives you've considered
Representing MyEnumType as a string instead would work, but using uint32s with String() string methods to create enums is idiomatic in my project, so this would be a break from convention. It depends whether the maintainers are interested in supporting this behaviour.
Additional context
I'd be happy to do the work to implement this myself but would first like to get input on which of the two solutions (if any) is preferred.
Is your feature request related to a problem? Please describe. I have a custom type that functions like an enum. In memory it's a
uint32
, but in JSON, it's represented as its string value by way of a customMarshalJSON
method:If I try to tag
MyResponse.MyValue
withenums:"First,Second"
, I get an error like:ParseComment error in file ... mypackage.MyResponse: myValue: enum value First can't convert to integer err: strconv.Atoi: parsing "First": invalid syntax
Describe the solution you'd like Either:
enumType:"string"
on an integer type.string
if no more specific type exists.Describe alternatives you've considered Representing
MyEnumType
as astring
instead would work, but usinguint32
s withString() string
methods to create enums is idiomatic in my project, so this would be a break from convention. It depends whether the maintainers are interested in supporting this behaviour.Additional context I'd be happy to do the work to implement this myself but would first like to get input on which of the two solutions (if any) is preferred.