Я хочу использовать сериализатор System.Text. Json Json с Cosmos. NET v3 SDK. Поэтому я использую:
var client = new CosmosClientBuilder
(accountEndpoint: "https://localhost:8081", "<key>")
.WithCustomSerializer(new SystemTextJsonCosmosSerializer(new JsonSerializerOptions {}))
.Build();
При использовании настраиваемого сериализатора (взято из 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);
}
}
Однако тип данных Point при этом будет некорректным serilized.
public Point Location { get; set; }
Должно быть (как в случае с Cosmos. NET SDK v3 / Newtonsoft, v4 Preview / System.Text. Json) быть:
"location": {
"type": "Point",
"coordinates": [
8.0000,
47.0000
]
},
Но вместо этого это заканчивается:
"location": {
"Position": {
"Coordinates": [
8.0000,
47.0000
],
"Longitude": 8.0000,
"Latitude": 47.0000,
"Altitude": null
},
"Crs": {
"Type": 0
},
"Type": 0,
"BoundingBox": null,
"AdditionalProperties": {}
},
У кого-нибудь есть идея, почему и как я могу заставить его сериализоваться должным образом?