Skip to content

Commit

Permalink
Serialize example values with empty arrays for responses
Browse files Browse the repository at this point in the history
  • Loading branch information
MaggieKimani1 committed Aug 2, 2024
1 parent 2250776 commit f63443f
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/Microsoft.OpenApi/Models/OpenApiMediaType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Writers;
Expand Down Expand Up @@ -76,7 +77,7 @@ public void SerializeAsV3(IOpenApiWriter writer)
writer.WriteOptionalObject(OpenApiConstants.Example, Example, (w, e) => w.WriteAny(e));

// examples
writer.WriteOptionalMap(OpenApiConstants.Examples, Examples, (w, e) => e.SerializeAsV3(w));
SerializeExamples(writer, Examples);

// encoding
writer.WriteOptionalMap(OpenApiConstants.Encoding, Encoding, (w, e) => e.SerializeAsV3(w));
Expand All @@ -94,5 +95,36 @@ public void SerializeAsV2(IOpenApiWriter writer)
{
// Media type does not exist in V2.
}

private void SerializeExamples(IOpenApiWriter writer, IDictionary<string, OpenApiExample> examples)
{
/* Special case for writing out empty arrays as valid response examples
* Check if there is any example with an empty array as its value
* */
var hasEmptyArray = examples.Values.Any(example =>
example.Value is OpenApiArray arr && arr.Count == 0
);

if (hasEmptyArray)
{
writer.WritePropertyName(OpenApiConstants.Examples);
writer.WriteStartObject();
foreach (var kvp in examples)
{
if (kvp.Value.Value is OpenApiArray arr && arr.Count == 0)
{
writer.WritePropertyName(kvp.Key);
writer.WriteStartObject();
writer.WriteRequiredObject(OpenApiConstants.Value, kvp.Value.Value, (w, v) => w.WriteAny(v));
writer.WriteEndObject();
}
}
writer.WriteEndObject();
}
else
{
writer.WriteOptionalMap(OpenApiConstants.Examples, examples, (w, e) => e.SerializeAsV3(w));
}
}
}
}

0 comments on commit f63443f

Please sign in to comment.