Example custom type to JSON
parent
2a3e657a82
commit
ff2749ed2c
@ -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…
Reference in New Issue