Spatial Point data type is not serialized correctly when using custom System.Text.Json serializer for Cosmos .NET v3 SDK

Viewed 291

I want to use the System.Text.Json Json serializer with the Cosmos .NET v3 SDK. So I use:

var client = new CosmosClientBuilder
        (accountEndpoint: "https://localhost:8081", "<key>")
        .WithCustomSerializer(new SystemTextJsonCosmosSerializer(new JsonSerializerOptions {}))
                .Build();

With the custom serializer being (taken from Github issue):

   public class SystemTextJsonCosmosSerializer : CosmosSerializer
    {
        private readonly JsonSerializerOptions _options;

        public SystemTextJsonCosmosSerializer(JsonSerializerOptions options)
        {
            _options = options;
        }

        /// <inheritdoc />
        public override T FromStream<T>(Stream stream)
        {
            // Have to dispose of the stream, otherwise the Cosmos SDK throws.
            // https://github.com/Azure/azure-cosmos-dotnet-v3/blob/0843cae3c252dd49aa8e392623d7eaaed7eb712b/Microsoft.Azure.Cosmos/src/Serializer/CosmosJsonSerializerWrapper.cs#L22
            // https://github.com/Azure/azure-cosmos-dotnet-v3/blob/0843cae3c252dd49aa8e392623d7eaaed7eb712b/Microsoft.Azure.Cosmos/src/Serializer/CosmosJsonDotNetSerializer.cs#L73
            using (stream)
            {
                // TODO Would be more efficient if CosmosSerializer supported async
                using var memory = new MemoryStream((int)stream.Length);
                stream.CopyTo(memory);

                byte[] utf8Json = memory.ToArray();

                return JsonSerializer.Deserialize<T>(utf8Json, _options);
            }
        }

        /// <inheritdoc />
        public override Stream ToStream<T>(T input)
        {
            byte[] utf8Json = JsonSerializer.SerializeToUtf8Bytes(input, _options);
            return new MemoryStream(utf8Json);
        }
    }

However, the Point data type is then not properly serilized.

public Point Location { get; set; }

It should be (as with Cosmos .NET SDK v3/Newtonsoft , v4 Preview/System.Text.Json) be:

    "location": {
        "type": "Point",
        "coordinates": [
            8.0000,
            47.0000
        ]
    },

But instead it ends up being:

    "location": {
        "Position": {
            "Coordinates": [
                8.0000,
                47.0000
            ],
            "Longitude": 8.0000,
            "Latitude": 47.0000,
            "Altitude": null
        },
        "Crs": {
            "Type": 0
        },
        "Type": 0,
        "BoundingBox": null,
        "AdditionalProperties": {}
    },

Anyone has idea on why, and how I can make it serialize properly?

0 Answers
Related