From ab747282c82e2db250b0cacd581bef383f1d8db3 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Sun, 1 Sep 2024 17:04:55 +0200 Subject: [PATCH] Add example for Nil value JSON unmarshaling Introduced ExampleVariable_UnmarshalJSON to demonstrate unmarshaling of JSON with nil and non-nil fields. This includes handling for multiple custom types and provides a sample output. Added necessary imports and error handling for clarity. --- niljson_test.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/niljson_test.go b/niljson_test.go index 106f3c9..40e0b64 100644 --- a/niljson_test.go +++ b/niljson_test.go @@ -7,6 +7,8 @@ package niljson import ( "bytes" "encoding/json" + "fmt" + "os" "testing" ) @@ -108,3 +110,48 @@ func TestVariable_UnmarshalJSON(t *testing.T) { t.Errorf("expected string to be nil after reset") } } + +func ExampleVariable_UnmarshalJSON() { + type JSONType struct { + Bool NilBoolean `json:"bool"` + ByteSlice NilByteSlice `json:"bytes"` + Float32 NilFloat32 `json:"float32,omitempty"` + Float64 NilFloat64 `json:"float64"` + Int NilInt `json:"int"` + Int64 NilInt64 `json:"int64"` + NullString NilString `json:"nilvalue,omitempty"` + String NilString `json:"string"` + } + data := []byte(`{ + "bytes": "Ynl0ZXM=", + "bool": true, + "float32": null, + "float64":0, + "int": 123, + "int64": 12345678901234, + "nilvalue": null, + "string":"test" + }`) + + var example JSONType + var output string + if err := json.Unmarshal(data, &example); err != nil { + fmt.Println("failed to unmarshal JSON:", err) + os.Exit(1) + } + + if example.Bool.NotNil() { + output += fmt.Sprintf("Bool is: %t, ", example.Bool.Value()) + } + if example.Float32.IsNil() { + output += "Float 32 is nil, " + } + if example.Float64.NotNil() { + output += fmt.Sprintf("Float 64 is: %f, ", example.Float64.Value()) + } + if example.String.NotNil() { + output += fmt.Sprintf("String is: %s", example.String.Value()) + } + fmt.Println(output) + // Output: Bool is: true, Float 32 is nil, Float 64 is: 0.000000, String is: test +}