Created
April 13, 2022 01:12
-
-
Save tmclnk/28f6b386049c536879f666d4a004b558 to your computer and use it in GitHub Desktop.
Golang Zero-Value JSON Serialization
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" | |
"github.com/stretchr/testify/assert" | |
"testing" | |
) | |
type MyType struct { | |
FieldA string `json:"field_a"` | |
FieldB string `json:"field_b,omitempty"` | |
// if we need to be able to omit a field OR use its zero-value, we'll need a pointer | |
FieldC *string `json:"field_c,omitempty"` | |
FieldD *string `json:"field_d,omitempty"` | |
FieldE *string `json:"field_e"` | |
} | |
func Test_EmptyStuff(t *testing.T) { | |
myString := "" | |
mySurcharge := MyType{ | |
FieldB: "", | |
FieldC: &myString, | |
} | |
bytes, err := json.MarshalIndent(mySurcharge, "", " ") | |
assert.Nil(t, err) | |
println(string(bytes)) | |
expected := `{ | |
"field_a": "", | |
"field_c": "", | |
"field_e": null | |
}` | |
assert.Equal(t, expected, string(bytes)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment