Skip to content

Commit

Permalink
fix: Observe serialization options in JsonEventFormatter for System.T…
Browse files Browse the repository at this point in the history
…ext.Json

Fixes cloudevents#225
  • Loading branch information
jskeet committed Aug 1, 2022
1 parent 72be5ff commit a0bfd26
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/CloudNative.CloudEvents.SystemTextJson/JsonEventFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ public override ReadOnlyMemory<byte> EncodeBatchModeMessage(IEnumerable<CloudEve
};

var stream = new MemoryStream();
var writer = new Utf8JsonWriter(stream);
var writer = CreateUtf8JsonWriter(stream);
writer.WriteStartArray();
foreach (var cloudEvent in cloudEvents)
{
Expand All @@ -422,12 +422,24 @@ public override ReadOnlyMemory<byte> EncodeStructuredModeMessage(CloudEvent clou
};

var stream = new MemoryStream();
var writer = new Utf8JsonWriter(stream);
var writer = CreateUtf8JsonWriter(stream);
WriteCloudEventForBatchOrStructuredMode(writer, cloudEvent);
writer.Flush();
return stream.ToArray();
}

private Utf8JsonWriter CreateUtf8JsonWriter(Stream stream)
{
var options = new JsonWriterOptions
{
Encoder = SerializerOptions?.Encoder,
Indented = SerializerOptions?.WriteIndented ?? false,
// TODO: Consider skipping validation in the future for the sake of performance.
SkipValidation = false
};
return new Utf8JsonWriter(stream, options);
}

private void WriteCloudEventForBatchOrStructuredMode(Utf8JsonWriter writer, CloudEvent cloudEvent)
{
Validation.CheckCloudEventArgument(cloudEvent, nameof(cloudEvent));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,21 @@ public void DecodeStructured_DefaultContentTypeToApplicationJson()
Assert.Equal("some text", jsonData.GetString());
}

[Fact]
public void EncodeStructured_IndentationSettings()
{
var cloudEvent = new CloudEvent().PopulateRequiredAttributes();
var formatter = new JsonEventFormatter(new JsonSerializerOptions
{
WriteIndented = true
}, new JsonDocumentOptions());
var encoded = formatter.EncodeStructuredModeMessage(cloudEvent, out _);
// Normalize the result to LF line endings.
var json = BinaryDataUtilities.GetString(encoded, Encoding.UTF8).Replace("\r\n", "\n").Replace("\r", "\n");
var expected = "{\n \"specversion\": \"1.0\",\n \"id\": \"test-id\",\n \"source\": \"//test\",\n \"type\": \"test-type\"\n}";
Assert.Equal(expected, json);
}

// Utility methods
private static object DecodeBinaryModeEventData(byte[] bytes, string contentType)
{
Expand Down

0 comments on commit a0bfd26

Please sign in to comment.