Convert iota List to String in JSON
·
389 words
·
2 minutes read
Constants in Go, when combined with iota
, can be a nice way to use options and settings as a list. We have an example below using genders to show this in action. The problem comes if you want to encode/decode structs to JSON, then the constant will be encoded into an int - sometimes it would be nice to convert this to a string to make it easier to represent what it is.
The Problem:
|
|
The Solution:
The solution is to use the same constant list, but create your own struct for this type. This is so we can add the MarshalJSON
and UnmarshalJSON
methods to it. These in turn then use maps to convert the constant into/from a string.
To make the example easier to read, we’ve split this into two files.
gender.go
|
|
main.go
|
|