Skip to content

Instantly share code, notes, and snippets.

@rossnelson
Created May 7, 2024 15:02
Show Gist options
  • Save rossnelson/319e0ccc31cd5d7d4742db337054206b to your computer and use it in GitHub Desktop.
Save rossnelson/319e0ccc31cd5d7d4742db337054206b to your computer and use it in GitHub Desktop.
how to marshaller
package something
import (
"encoding/json"
"strconv"
)
type SomeData struct {
SomeSlice []int `json:"some_slice"`
}
func (sd *SomeData) AsStrings() []string {
strings := []string{}
for _, id := range sd.SomeSlice {
strings = append(strings, string(id))
}
return strings
}
func (sd *SomeData) MarshalJSON() ([]byte, error) {
type Alias SomeData
return json.Marshal(&struct {
SomeSlice []string `json:"some_slice"`
*Alias
}{
Alias: (*Alias)(sd),
SomeSlice: sd.AsStrings(),
})
}
func (sd *SomeData) UnmarshalJSON(data []byte) error {
type Alias SomeData
aux := &struct {
SomeSlice []string `json:"some_slice"`
*Alias
}{
Alias: (*Alias)(sd),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
sd.SomeSlice = []int{}
for _, str := range aux.SomeSlice {
i, _ := strconv.Atoi(str)
sd.SomeSlice = append(sd.SomeSlice, i)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment