Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stnguyen90/6eafc320709412b9f90cda3d18c547bc to your computer and use it in GitHub Desktop.
Save stnguyen90/6eafc320709412b9f90cda3d18c547bc to your computer and use it in GitHub Desktop.
Handling Null JSON Arrays in Go - Custom Marshaler
package main
import (
"encoding/json"
"fmt"
)
// Bag holds items
type Bag struct {
Items []string
}
// MarshalJSON initializes nil slices and then marshals the bag to JSON
func (b Bag) MarshalJSON() ([]byte, error) {
type Alias Bag
a := struct {
Alias
}{
Alias: (Alias)(b),
}
if a.Items == nil {
a.Items = make([]string, 0)
}
return json.Marshal(a)
}
// PrintJSON converts payload to JSON and prints it
func PrintJSON(payload interface{}) {
response, _ := json.Marshal(payload)
fmt.Printf("%s\n", response)
}
func main() {
bag1 := Bag{}
PrintJSON(bag1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment