Created
June 24, 2016 10:02
-
-
Save khoden/73e378071f713027f68e8a5e4878eac9 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" | |
| ) | |
| type Sale struct { | |
| Description string | |
| } | |
| func (s *Sale) ToMap() map[string]interface{} { | |
| return map[string]interface{}{ | |
| "description": s.Description, | |
| } | |
| } | |
| func (s *Sale) MarshalJSON() ([]byte, error) { | |
| return json.Marshal(s.ToMap()) | |
| } | |
| type Payment struct { | |
| ID int | |
| Sale *Sale | |
| } | |
| func (p *Payment) ToMap() map[string]interface{} { | |
| return map[string]interface{}{ | |
| "id": p.ID, | |
| "sale": Map(p.Sale), | |
| } | |
| } | |
| func (p *Payment) MarshalJSON() ([]byte, error) { | |
| return json.Marshal(p.ToMap()) | |
| } | |
| type Mapper interface { | |
| ToMap() map[string]interface{} | |
| } | |
| func Map(m Mapper) (result map[string]interface{}) { | |
| if m == nil { | |
| return nil | |
| } else { | |
| return m.ToMap() | |
| } | |
| } | |
| func main() { | |
| var emptySale *Sale | |
| payment := &Payment{ID:2, Sale:emptySale} | |
| fmt.Println(payment.MarshalJSON()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment