From 00f85858b87feb557a7de640aa9d99cb52d0e8e2 Mon Sep 17 00:00:00 2001 From: Ronald K <43806892+rkodev@users.noreply.github.com> Date: Mon, 12 Feb 2024 14:51:54 +0300 Subject: [PATCH] Fixes serialization of null in a collection of objects (#129) * Adds serialization of null in a collection' * Fix test --- CHANGELOG.md | 6 ++++++ json_serialization_writer.go | 13 ++++++++++--- json_serialization_writer_test.go | 20 ++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c32a2e9..9932d2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [1.0.6] - 2024-02-12 + +### Changed + +- Fixes serilaization of `null` values in collections of Objects. + ## [1.0.5] - 2024-01-10 ### Changed diff --git a/json_serialization_writer.go b/json_serialization_writer.go index f1f60b7..2da8a7f 100644 --- a/json_serialization_writer.go +++ b/json_serialization_writer.go @@ -331,9 +331,16 @@ func (w *JsonSerializationWriter) WriteCollectionOfObjectValues(key string, coll } w.writeArrayStart() for _, item := range collection { - err := w.WriteObjectValue("", item) - if err != nil { - return err + if item != nil { + err := w.WriteObjectValue("", item) + if err != nil { + return err + } + } else { + err := w.WriteNullValue("") + if err != nil { + return err + } } w.writePropertySeparator() } diff --git a/json_serialization_writer_test.go b/json_serialization_writer_test.go index 678adb4..57aa683 100644 --- a/json_serialization_writer_test.go +++ b/json_serialization_writer_test.go @@ -215,6 +215,26 @@ func TestWriteInvalidAdditionalData(t *testing.T) { assert.True(t, IsJSON("{"+stringResult+"}")) } +func TestWriteACollectionWithNill(t *testing.T) { + serializer := NewJsonSerializationWriter() + value := "value" + serializer.WriteStringValue("key", &value) + + prop1Value1 := internal.NewTestEntity() + idIntValue1 := "11" + prop1Value1.SetId(&idIntValue1) + + collection := []absser.Parsable{nil, prop1Value1} + err := serializer.WriteCollectionOfObjectValues("", collection) + + assert.Nil(t, err) + result, err := serializer.GetSerializedContent() + + stringResult := string(result[:]) + assert.Contains(t, stringResult, "null,") + assert.Contains(t, stringResult, "\"key\":\"value\",[null,{\"id\":\"11\"}]") +} + func IsJSON(str string) bool { var js json.RawMessage err := json.Unmarshal([]byte(str), &js)