Skip to content

Commit ffb3c0f

Browse files
authored
Relax JSON encoding in System.ClientModel (Azure#50885)
The default encoding rules used by Utf8JsonWriter are very strict, more than what's needed just for JSON, under the assumption that the resulting JSON might be embedded in an HTML page / script element. That strictness is not necessary or desirable when JSON is just being sent as part of an application/json payload, as it is with API inputs/outputs. The stricter encoding rules can have measurable impact, especially with the kinds of payloads commonly used in these APIs, e.g. base64 includes '+' in its alphabet, and '+' is a character that's encoded in the strict mode and not in the relaxed mode. This PR relaxes the encoding rules used.
1 parent 5caa16f commit ffb3c0f

File tree

2 files changed

+4
-2
lines changed

2 files changed

+4
-2
lines changed

sdk/core/System.ClientModel/src/ModelReaderWriter/JsonCollectionWriter.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
using System.ClientModel.Internal;
55
using System.Collections;
6+
using System.Text.Encodings.Web;
67
using System.Text.Json;
78

89
namespace System.ClientModel.Primitives;
@@ -12,7 +13,7 @@ internal class JsonCollectionWriter : CollectionWriter
1213
internal override BinaryData Write(IEnumerable enumerable, ModelReaderWriterOptions options)
1314
{
1415
using UnsafeBufferSequence sequenceWriter = new();
15-
using Utf8JsonWriter writer = new(sequenceWriter);
16+
using Utf8JsonWriter writer = new(sequenceWriter, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
1617
WriteEnumerable(enumerable, writer, options);
1718
writer.Flush();
1819
return sequenceWriter.ExtractReader().ToBinaryData();

sdk/core/System.ClientModel/src/ModelReaderWriter/ModelWriterOfT.cs

Lines changed: 2 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.ClientModel.Primitives;
5+
using System.Text.Encodings.Web;
56
using System.Text.Json;
67

78
namespace System.ClientModel.Internal;
@@ -29,7 +30,7 @@ public ModelWriter(IJsonModel<T> model, ModelReaderWriterOptions options)
2930
public UnsafeBufferSequence.Reader ExtractReader()
3031
{
3132
using UnsafeBufferSequence sequenceWriter = new UnsafeBufferSequence();
32-
using var jsonWriter = new Utf8JsonWriter(sequenceWriter);
33+
using var jsonWriter = new Utf8JsonWriter(sequenceWriter, new JsonWriterOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
3334
_model.Write(jsonWriter, _options);
3435
jsonWriter.Flush();
3536
return sequenceWriter.ExtractReader();

0 commit comments

Comments
 (0)