Created
June 12, 2023 13:31
-
-
Save Khoulaiz/f13a52c5403138fc2af31dab2e313a9d to your computer and use it in GitHub Desktop.
JSON marshalling with dynamic omitempty setting
This file contains hidden or 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" | |
) | |
type Nullable[T any] struct { | |
val *T | |
} | |
func (n *Nullable[T]) MarshalJSON() ([]byte, error) { | |
x, err := json.Marshal(n.val) | |
return x, err | |
} | |
func (n *Nullable[T]) UnmarshalJSON(data []byte) error { | |
var v T | |
x := json.Unmarshal(data, &v) | |
n.val = &v | |
return x | |
} | |
type JsonStruct struct { | |
StringFilled *Nullable[string] `json:"stringFilled,omitempty"` | |
StringUnknown *Nullable[string] `json:"stringUnknown,omitempty"` | |
StringNotShown *Nullable[string] `json:"stringNotShown,omitempty"` | |
ArrayFilled *Nullable[[]string] `json:"arrayFilled,omitempty"` | |
ArrayUnknown *Nullable[[]string] `json:"arrayUnknown,omitempty"` | |
ArrayNotShown *Nullable[[]string] `json:"arrayNotShown,omitempty"` | |
} | |
func main() { | |
var result JsonStruct | |
filledString := "filled value" | |
filledArray := []string{"a", "b", "c"} | |
result.StringFilled = &Nullable[string]{val: &filledString} // normal value | |
result.StringUnknown = &Nullable[string]{val: nil} // value = null | |
result.StringNotShown = nil // will not appear at all | |
result.ArrayFilled = &Nullable[[]string]{val: &filledArray} | |
result.ArrayUnknown = &Nullable[[]string]{val: nil} | |
result.ArrayNotShown = nil | |
b, err := json.MarshalIndent(result, "", " ") | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("%s\n", b) | |
var readStruct JsonStruct | |
err = json.Unmarshal(b, &readStruct) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment