Last active
March 25, 2024 11:34
-
-
Save joseph0x45/d40d1f5ec73dd9bca415600db3fba70b to your computer and use it in GitHub Desktop.
Go json.Marshaler and json.Unmarshaler interfaces
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" | |
| "strconv" | |
| ) | |
| func pigeonAgeToHumanYears(pigeonYears int) int { | |
| if pigeonYears <= 1 { | |
| return pigeonYears * 5 | |
| } | |
| return 5 + (pigeonYears-1)*2 | |
| } | |
| type PigeonYear int | |
| type Pigeon struct { | |
| Name string `json:"name"` | |
| Age PigeonYear `json:"age"` | |
| Experience PigeonYear `json:"experience"` | |
| Rating int `json:"rating"` | |
| Booked bool `json:"booked"` | |
| } | |
| func (p PigeonYear) MarshalJSON() ([]byte, error) { | |
| humanYears := pigeonAgeToHumanYears(int(p)) | |
| jsonValue := fmt.Sprintf("%d years old (%d in human years)", p, humanYears) | |
| quotedJsonValue := strconv.Quote(jsonValue) | |
| return []byte(quotedJsonValue), nil | |
| } | |
| func (p *PigeonYear) UnmarshalJSON(data []byte) error { | |
| var intData int | |
| if err := json.Unmarshal(data, &intData); err != nil { | |
| return err | |
| } | |
| *p = PigeonYear(intData) | |
| return nil | |
| } | |
| func main() { | |
| Percy := Pigeon{ | |
| Name: "Percy", | |
| Age: 3, | |
| Experience: 2, | |
| Rating: 4, | |
| Booked: true, | |
| } | |
| data, err := json.MarshalIndent(Percy, "", " ") | |
| if err != nil { | |
| panic(err) | |
| } | |
| fmt.Println(string(data)) | |
| pigeonJSON := []byte(`{"name":"Percy","age":3,"experience":2,"rating":4,"booked":true}`) | |
| var pigeon Pigeon | |
| if err := json.Unmarshal(pigeonJSON, &pigeon); err != nil { | |
| fmt.Println("Error decoding JSON:", err) | |
| return | |
| } | |
| fmt.Println("Decoded Pigeon:", pigeon) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment