radzen-blazor icon indicating copy to clipboard operation
radzen-blazor copied to clipboard

ODataJsonSerializer does not respect given Converters from the JsonSerializerOptions

Open gordon-matt opened this issue 10 months ago • 2 comments

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

gordon-matt avatar Jun 20 '25 09:06 gordon-matt

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:

  1. Can you please have some option to enable the default OData behaviour of strings for enums?

  2. 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?

gordon-matt avatar Jun 20 '25 10:06 gordon-matt

This thread might help you: https://forum.radzen.com/t/enums-break-readasync/9480

enchev avatar Jun 20 '25 10:06 enchev

Yeah my fault. I forgot to add [JsonConverter(typeof(JsonStringEnumConverter))] to the property itself.

gordon-matt avatar Jun 24 '25 08:06 gordon-matt