ODataJsonSerializer does not respect given Converters from the JsonSerializerOptions
Describe the bug ODataJsonSerializer does not respect given Converters from the JsonSerializerOptions
To Reproduce Have an entity with an enum property.. then try post it with passing in a JsonStringEnumConverter:
var jsonOptions = new JsonSerializerOptions
{
Converters = { new JsonStringEnumConverter() }
};
var uri = new Uri(httpClient.BaseAddress, $"/odata/{entitySetName}");
using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uri)
{
Content = new StringContent(
ODataJsonSerializer.Serialize(entity, jsonOptions), // <-- Here
Encoding.UTF8,
"application/json")
};
ODataJsonSerializer still serializes the enum as a number anyway.
Expected behavior ODataJsonSerializer should respect the formatters being passed in. This is needed, as I get a ModelState error from the API when a number is passed instead of the string:
Cannot read the value '0' as a quoted JSON string value.
Desktop (please complete the following information):
- OS: Windows
- Browser: FireFox
It seems it's not just posting, but reading enum values it has an issue with:
Example:
var data = await response.ReadAsync<ODataServiceResult<TEntity>>();
Produces this error:
The JSON value could not be converted to TestApp.Data.Entities.FieldType. Path: $.value[0].FieldType | LineNumber: 0 | BytePositionInLine: 128.'
I believe the OData spec is for enums to be strings, not numbers. If the Radzen helpers are going to expect numbers as the default, then:
-
Can you please have some option to enable the default OData behaviour of strings for enums?
-
If numbers is recommended for some reason, show us how to configure our OData APIs to serialize/deserialize enums as numbers instead of strings. Did I miss this in the docs somewhere?
This thread might help you: https://forum.radzen.com/t/enums-break-readasync/9480
Yeah my fault. I forgot to add [JsonConverter(typeof(JsonStringEnumConverter))] to the property itself.