Example custom type to JSON

main
Drew Bednar 8 hours ago
parent 2a3e657a82
commit ff2749ed2c

@ -9,7 +9,13 @@ type Movie struct {
CreatedAt time.Time `json:"-"` // omits always
Title string `json:"title"`
Year int32 `json:"year,omitzero"`
Runtime int32 `json:"runtime,omitzero"`
Genres []string `json:"genres,omitzero"`
Version int32 `json:"version"`
// Runtime int32 `json:"runtime,omitzero"`
// Use the Runtime type instead of int32. Note that the omitzero directive will
// still work on this: if the Runtime field has the underlying value 0, then it will
// be considered zero and omitted -- and the MarshalJSON() method we just made
// won't be called at all.
// VSCode will complain though about reflection issue
Runtime Runtime `json:"runtime,omitzero`
Genres []string `json:"genres,omitzero"`
Version int32 `json:"version"`
}

@ -0,0 +1,27 @@
package data
import (
"fmt"
"strconv"
)
// Declare a custom Runtime type, which has the underlying int32 type
type Runtime int32
// The rule about pointers vs. values for receivers is that value methods
// can be invoked on pointers and values, but pointer methods can only
// be invoked on pointers.
// Implements json.Marshaler interface.
func (r Runtime) MarshalJSON() ([]byte, error) {
// Generate a string containing the movie runtime
jsonValue := fmt.Sprintf("%d mins", r)
//Use strconv.Quote() function on the string to wrap it in double quotes
// necessary to be valid json
quotedJSONValue := strconv.Quote(jsonValue)
// convert the string to byte slice and return it
return []byte(quotedJSONValue), nil
}
Loading…
Cancel
Save