microsoft / kiota-dotnet

Abstractions library for the Kiota generated SDKs in dotnet
https://aka.ms/kiota/docs
MIT License
32 stars 29 forks source link

Pass relevant `JsonWriterOptions` from the `KiotaJsonSerializationContext.Options` to the `Utf8JsonWriter` when writing json to enable customization. #281

Closed andrueastman closed 1 month ago

andrueastman commented 2 months ago

Related to discussion at https://github.com/microsoft/kiota/discussions/4898#discussioncomment-9949732

Trying out the code below, the Encode settings seem to have no effect on the serialized payload.

        var jsonSerializationOptions = new JsonSerializerOptions
        {
            WriteIndented = true,
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };
        var kiotaJsonSerializationContext = new KiotaJsonSerializationContext(jsonSerializationOptions); // create serialization context with custom options
        SerializationWriterFactoryRegistry.DefaultInstance.ContentTypeAssociatedFactories["application/json"] = new JsonSerializationWriterFactory(kiotaJsonSerializationContext); // replace the json serializer with one with custom options

        var requestJson = await KiotaJsonSerializer.SerializeAsStringAsync(request);

This is because, the JsonSerializationWriter initializes a Utf8JsonWriter instance without propagating relelvant options to the JsonWriterOptions parameter in the constructor here.

https://github.com/microsoft/kiota-serialization-json-dotnet/blob/046356f4e43767b12cfa7b6d223671d83e63309c/src/JsonSerializationWriter.cs#L51

The line should probably be updated to something as below and relevant tests added.

writer = new Utf8JsonWriter(_stream, new JsonWriterOptions {
    Encoder = kiotaJsonSerializationContext.Options.Encoder,
    Indented = kiotaJsonSerializationContext.Options.WriteIndented
});
andrueastman commented 2 months ago

Transferring issue as part of https://github.com/microsoft/kiota-abstractions-dotnet/issues/238