Last active
June 22, 2019 17:23
-
-
Save tetafro/f83a62f234e3d725289dcc243d76020b to your computer and use it in GitHub Desktop.
Example for changing default JSON marshalling-unmarshalling
This file contains 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
Naming file |
This file contains 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
// Structure for marshalling/unmarshalling | |
type Message struct { | |
Id int `json:"id"` | |
Date time.Time `json:"date"` | |
} | |
// Custom marshalling: date field will be converted | |
// to int64 (unix timestamp) | |
func (m *Message) MarshalJSON() ([]byte, error) { | |
type Alias Message | |
return json.Marshal(&struct { | |
Date int64 `json:"date"` | |
*Alias | |
}{ | |
SendDate: m.Date.Unix(), | |
Alias: (*Alias)(m), | |
}) | |
} | |
// Custom unmarshalling: date field will be converted | |
// from integer (unix timestamp) to time.Time | |
func (m *Message) UnmarshalJSON(data []byte) error { | |
type Alias Message | |
tmp := &struct { | |
Date int64 `json:"date"` | |
*Alias | |
}{ | |
Alias: (*Alias)(m), | |
} | |
if err := json.Unmarshal(data, &tmp); err != nil { | |
return err | |
} | |
m.Date = time.Unix(tmp.Date, 0) | |
return nil | |
} | |
func main() { | |
m := Message{ | |
Id: 10, | |
Date: time.Now(), | |
} | |
j := json.Marshal(&m) | |
u := json.Unmarshal(j) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment