I am currently using .NET 6 and System.Text.Json for serialization. I am having issues where system.text.json does not deserialize the enum to string properly when I return the response using OkObjectResult or ObjectResult
I have used the following on model
public class Customer
{
public string? id { get; set; }
public string? Name { get; set; }
public string Address { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter))]
public CustomerType Type {get; set;}
}
using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum CustomerType
{
NEW,
EXISTING
}
Now the API Code
public async Task<IActionResult> GetCustomerById(string Id)
{
var results = await _customerService.GetData(Id);
// The results have correct JSON data with enum as string but as soon as I pass this to OkObjectResult, it changes the enum back to int
return new OkObjectResult(results );
}
Service
public async Task<Customer> GetData(string Id)
{
var results = await _httpClient.SendAsync(Id); // Get Data
var jsonResults = await results.Content.ReadAsStringAsync();
var options = new JsonSerializerOptions{ Converters ={
new JsonStringEnumConverter()};
return JsonSerializer.Deserialize<Customer>(jsonResults ,
options ) ; // This returns the data correctly
}
Now my question why OkObjectResult breaks the code and return the integer instead of enum string value
One of the reason can be related to the fact that you are registering multiple Json serialize options: Jsone & NewtonsoftJson at the same time.
Keeping only one may resolve the issue.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With