Created
October 4, 2014 14:32
-
-
Save smagch/e3a26b16413015742568 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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