Skip to content

Commit f63443f

Browse files
committed
Serialize example values with empty arrays for responses
1 parent 2250776 commit f63443f

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/Microsoft.OpenApi/Models/OpenApiMediaType.cs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT license.
33

44
using System.Collections.Generic;
5+
using System.Linq;
56
using Microsoft.OpenApi.Any;
67
using Microsoft.OpenApi.Interfaces;
78
using Microsoft.OpenApi.Writers;
@@ -76,7 +77,7 @@ public void SerializeAsV3(IOpenApiWriter writer)
7677
writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, e) => w.WriteAny(e));
7778

7879
// examples
79-
writer.WriteOptionalMap(OpenApiConstants.Examples, Examples, (w, e) => e.SerializeAsV3(w));
80+
SerializeExamples(writer, Examples);
8081

8182
// encoding
8283
writer.WriteOptionalMap(OpenApiConstants.Encoding, Encoding, (w, e) => e.SerializeAsV3(w));
@@ -94,5 +95,36 @@ public void SerializeAsV2(IOpenApiWriter writer)
9495
{
9596
// Media type does not exist in V2.
9697
}
98+
99+
private void SerializeExamples(IOpenApiWriter writer, IDictionary<string, OpenApiExample> examples)
100+
{
101+
/* Special case for writing out empty arrays as valid response examples
102+
* Check if there is any example with an empty array as its value
103+
* */
104+
var hasEmptyArray = examples.Values.Any(example =>
105+
example.Value is OpenApiArray arr && arr.Count == 0
106+
);
107+
108+
if (hasEmptyArray)
109+
{
110+
writer.WritePropertyName(OpenApiConstants.Examples);
111+
writer.WriteStartObject();
112+
foreach (var kvp in examples)
113+
{
114+
if (kvp.Value.Value is OpenApiArray arr && arr.Count == 0)
115+
{
116+
writer.WritePropertyName(kvp.Key);
117+
writer.WriteStartObject();
118+
writer.WriteRequiredObject(OpenApiConstants.Value, kvp.Value.Value, (w, v) => w.WriteAny(v));
119+
writer.WriteEndObject();
120+
}
121+
}
122+
writer.WriteEndObject();
123+
}
124+
else
125+
{
126+
writer.WriteOptionalMap(OpenApiConstants.Examples, examples, (w, e) => e.SerializeAsV3(w));
127+
}
128+
}
97129
}
98130
}

0 commit comments

Comments
 (0)