Created
May 7, 2024 15:02
-
-
Save rossnelson/319e0ccc31cd5d7d4742db337054206b to your computer and use it in GitHub Desktop.
how to marshaller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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