Skip to content

Instantly share code, notes, and snippets.

@khoden
Created June 24, 2016 10:02
Show Gist options
  • Select an option

  • Save khoden/73e378071f713027f68e8a5e4878eac9 to your computer and use it in GitHub Desktop.

Select an option

Save khoden/73e378071f713027f68e8a5e4878eac9 to your computer and use it in GitHub Desktop.
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