Skip to content

Instantly share code, notes, and snippets.

@smagch
Created October 4, 2014 14:32
Show Gist options
  • Select an option

  • Save smagch/e3a26b16413015742568 to your computer and use it in GitHub Desktop.

Select an option

Save smagch/e3a26b16413015742568 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type Role int
func (r Role) MarshalJSON() ([]byte, error) {
if r == 1 {
return []byte(`"owner"`), nil
} else if r == 2 {
return []byte(`"editor"`), nil
}
return nil, fmt.Errorf("Invalid role id: %d", r)
}
func (r Role) UnmarshalJSON(b []byte) error {
roleName := strings.ToLower(string(b))
switch roleName {
case `"owner"`:
r = 1
case `"editor"`:
r = 2
default:
return fmt.Errorf("Invalid role: %s", roleName)
}
return nil
}
type Member struct {
Name string `json:"name"`
Role Role `json:"role"`
}
func main() {
m := &Member{"Tomoya", 1}
b, err := json.Marshal(m)
if err != nil {
log.Fatal(err)
}
fmt.Println("Hello, playground: ", string(b[:]))
b = []byte(`{"name":"Shimaguchi Tomoya","role": "oWner" }`)
if err = json.Unmarshal(b, &m); err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", m)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment