Custom marshaling/unmarshaling of object keys
Maps are marshaled/unmarshaled as JSON objects. But if you have a map that has keys other than a string type, how can you marshal/unmarshal it to JSON?
How to do it...
The solution depends on the exact type of the key:
- Maps with key types derived from string or integer types can be marshaled/unmarshaled using the standard library methods:
type Key int64 func main() { var m map[Key]int err := json.Unmarshal([]byte(`{"123":123}`), &m) if err!=nil { panic(err) } fmt.Println(m[123]) // Prints 123 }
- If map keys require additional processing for marshaling/unmarshaling, implement the
encoding.TextMarshaler
andencoding.TextUnmarshaler
interfaces:// Key is an uint that is encoded as an hex strings for JSON key type Key uint func (k *Key...