Skip to content

Commit 8874712

Browse files
authored
Merge pull request #18 from dotarj/fix-empty-array
fix empty array is removed from json response #11
2 parents f35f6f3 + 8909179 commit 8874712

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/PartialResponse.AspNetCore.Mvc.Formatters.Json/Internal/JsonSerializerExtensions.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,17 @@ public static void Serialize(this JsonSerializer jsonSerializer, JsonWriter json
6262

6363
private static void RemoveArrayElements(JArray array, string currentPath, SerializerContext context)
6464
{
65+
var containsChildItems = array.Count > 0;
66+
6567
array.OfType<JObject>()
6668
.ToList()
6769
.ForEach(childObject => RemoveObjectProperties(childObject, currentPath, context));
6870

69-
RemoveArrayIfEmpty(array);
71+
// PartialResponse should only remove an array when it initially contained items, but was empty after filtering.
72+
if (containsChildItems)
73+
{
74+
RemoveArrayIfEmpty(array);
75+
}
7076
}
7177

7278
private static void RemoveArrayIfEmpty(JArray array)

test/PartialResponse.AspNetCore.Mvc.Formatters.Json.Test/JsonSerializerExtensionsTests.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,5 +174,18 @@ public void TheSerializeMethodFilterCorrectlyUsingCache()
174174
// Assert
175175
Assert.Equal("[{\"foo\":\"bar\"},{\"foo\":\"bar\"}]", result.ToString());
176176
}
177+
178+
[Fact]
179+
public void TheSerializeMethodShouldFilterArrayElementInsideArrayElement2()
180+
{
181+
// Arrange
182+
var value = new { totalCount = 0, data = new object[0] };
183+
184+
// Act
185+
jsonSerializer.Serialize(this.jsonWriter, value, _ => true);
186+
187+
// Assert
188+
Assert.Equal("{\"totalCount\":0,\"data\":[]}", result.ToString());
189+
}
177190
}
178191
}

0 commit comments

Comments
 (0)