I am integrating some API and getting variant response for error field
{ "errors" : "amar" }
{ "errors" : "akbar" }
{ "error" : "anthony" }
My error handling class has one property string Error
.
How can I deserialize in an efficient way in that without try catch
? I am using .NET Core 8.0
For array of strings, I can have comma-separated errors.
My model for class looks like this at the moment:
public record ApiResponseError([property: JsonPropertyName("error")] string Error)
3
Answers
According to your description, you could create a custom json converter to handle the json for the APIERROR record.
You could create the converter like below:
Register it inside the program.cs
Test with the controller
Result:
and
You could create a custom converter. Would be something like this
Finally decorate your response class with the
JsonConverterAttribute
In .Net 8 some new attributes came into play, which help to solve this without writing your own converter:
You can test the different JSONs with this little program:
This would make the desired usage of the property better, but unfortunately this doesn’t work: