Last active
July 12, 2020 00:36
-
-
Save stnguyen90/6eafc320709412b9f90cda3d18c547bc to your computer and use it in GitHub Desktop.
Handling Null JSON Arrays in Go - Custom Marshaler
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" | |
) | |
// 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