In an endpoint Im developing I use the following command
var responseBodyDeserialized = await JsonSerializer.DeserializeAsync<TResponse>(response.Content.ReadAsStream());
The issue is that one of the fields its throwing an exception. Because the value can be for example:
- 0 (number)
- "10" (string)
- "7+" (string)
the property of TResponse I already tried to give the type string and int and both are throwing exceptions.
var jsonOptions = new JsonSerializerOptions()
{
NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals
};
Using this JsonSerializerOptions and having the property with type int doesnt work because we can get a string like "7+".
Is there a string handler we can use?
The exception are like this:
{"The JSON value could not be converted to System.Int32. Path: $[111].xxxxxx | LineNumber: 0 | BytePositionInLine: 11569963."}
UPDATE:
One solution I found to solve this is to use the type object since the property can either be received from json as int or string types.
And then since I want to convert it to another DTO I'm using AutoMapper library and user a map like the one above:
CreateMap<FeedElemDto, ResultDto>()
.ForMember(dest => dest.xxxx, opt => opt.MapFrom(src => Convert.ToString(src.xxxx)));
Would like to know if this is an OK solution.