Given the following JSON object
[
{
"change_date": "20211118 2134",
"inspection_id": "74207177",
"insp_unit_id": "185883333",
}
]
And the following C# class.
public class Root
{
public string change_date { get; set; }
public string inspection_id { get; set; }
public string insp_unit_id { get; set; }
}
What is a good way to return int’s instead of strings. I’m currently adding methods to the class like below.
public int inspection_id_int()
{
return Convert.toint32(inspection_id );
}
Looking for advice on a better way to achieve this. I’m using System.Text.JSON and deserializing via JsonSerializer.Deserialize.
3
Answers
It’s better to check if you can convert the value directly to int else, you will run into exception.
Generally, data from an API should follow the API’s schema, so you would use a string property for the data object since that’s how it is serialized.
You could then use another class to represent the actual object you want to use in your app, and map from the
int
to thestring
when creating your objects from the API data.AutoMapper
is a good library to make most of these mappings trivial, and lets you use custom mappings that could be much more complex than just converting a string to an integer (or a date, as you probably need for thechange_date
field.The process would be something like:
You could do the following:
Create your own converter
decorate your class and change property to int
Then it will work as you expected