Skip to content

Instantly share code, notes, and snippets.

@17twenty
Created May 21, 2020 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 17twenty/52f294f67cccdbd7370a2bd9dcafd21d to your computer and use it in GitHub Desktop.
Save 17twenty/52f294f67cccdbd7370a2bd9dcafd21d to your computer and use it in GitHub Desktop.
Implementing Custom Marshal / Unmarshal for a custom type (and using an interface)
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"strconv"
)
type Farter interface {
Fart() string
}
func DoAFartAsJSON(f Farter) {
log.Println("Farting:", f.Fart())
json.NewEncoder(os.Stdout).Encode(f)
}
func main() {
a := make(Stuff)
a[1] = "asdf"
a[-1] = "qwer"
log.Println("Initial: ", a)
stuff, err := json.Marshal(a)
log.Println("Serialized: ", string(stuff), err)
b := make(Stuff)
err = json.Unmarshal(stuff, &b)
log.Println("Deserialized:", b, err)
DoAFartAsJSON(a)
}
type Stuff map[int]string
func (this Stuff) Fart() string {
return "pfft"
}
func (this Stuff) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString("{")
length := len(this)
count := 0
for key, value := range this {
jsonValue, err := json.Marshal(value)
if err != nil {
return nil, err
}
buffer.WriteString(fmt.Sprintf("\"%d\":%s", key, string(jsonValue)))
count++
if count < length {
buffer.WriteString(",")
}
}
buffer.WriteString("}")
return buffer.Bytes(), nil
}
func (this Stuff) UnmarshalJSON(b []byte) error {
var stuff map[string]string
err := json.Unmarshal(b, &stuff)
if err != nil {
return err
}
for key, value := range stuff {
numericKey, err := strconv.Atoi(key)
if err != nil {
return err
}
this[numericKey] = value
}
return nil
}
@17twenty
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment