Senior
How to override the way a structure field is converted to JSON?
sobes.tech AI
Answer from AI
In Go, to override the way a struct field is converted to JSON, you can implement the json.Marshaler interface for the entire struct or for a specific field if it is a type with a MarshalJSON() method. This allows you to define custom serialization logic.
Example for a field with a custom type:
package main
import (
"encoding/json"
"fmt"
)
type CustomType int
func (c CustomType) MarshalJSON() ([]byte, error) {
// Convert the number to a string with a prefix
return json.Marshal(fmt.Sprintf("custom-%d", c))
}
type MyStruct struct {
Field CustomType `json:"field"`
}
func main() {
s := MyStruct{Field: 42}
data, _ := json.Marshal(s)
fmt.Println(string(data)) // Output: {"field":"custom-42"}
}
If you want to change the serialization of the entire struct, implement the MarshalJSON() method for the struct as a whole.