Last active
October 20, 2021 21:00
-
-
Save Javlopez/0ff6ec71d2ebf8ede4d9844d2f0771a5 to your computer and use it in GitHub Desktop.
Custom unmarshal
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
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"strings" | |
"time" | |
) | |
type DateCreatedAt time.Time | |
type Message struct { | |
User string `json:"user"` | |
DateCreatedAt DateCreatedAt `json:"date_created"` | |
Body string `json:"body"` | |
} | |
const ctLayout = "2006-01-02 15:04:05Z07:00" | |
func (j *DateCreatedAt) UnmarshalJSON(b []byte) error { | |
s := strings.Trim(string(b), `"`) | |
t, err := time.Parse(ctLayout, s) | |
if err != nil { | |
return err | |
} | |
*j = DateCreatedAt(t) | |
return nil | |
} | |
// MarshalJSON writes a quoted string in the custom format | |
func (j DateCreatedAt) MarshalJSON() ([]byte, error) { | |
return []byte(j.String()), nil | |
} | |
// Maybe a Format function for printing your date | |
// String returns the time in the custom format | |
func (j *DateCreatedAt) String() string { | |
t := time.Time(*j) | |
return fmt.Sprintf("%q", t.Format(ctLayout)) | |
} | |
func main() { | |
var msg Message | |
jsonData := `{"user": "d0cc39e3-a976-5dbe-869f-87283d7e3e1c", "date_created": "2020-12-17 19:36:50+00:00", "body": "The content"}` | |
json.Unmarshal([]byte(jsonData), &msg) | |
//----- output --------- | |
//message: "2020-12-17 19:36:50Z" | |
//------------------ | |
fmt.Printf("message: %+v", msg.DateCreatedAt.String()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment