Search code examples
c#jsondeserialization

Better way to convert strings in json object to ints in c# class


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.


Solution

  • It depends on what you want to have as int, change_date is not valid number (has space in the middle).

    But when it comes to other fields, just decalre them as int

    class Root
    {
        public string change_date { get; set; }
        public int inspection_id { get; set; }
        public int insp_unit_id { get; set; }
    }
    

    and then pass JsonSerializerOptions with NumberHandling = JsonNumberHandling.AllowReadingFromString to Deserialize method:

    var json = @"[
      {
        ""change_date"": ""20211118 2134"",
        ""inspection_id"": ""74207177"",
        ""insp_unit_id"": ""185883333""
      }
    ]";
    
    var root = JsonSerializer.Deserialize<Root[]>(
        json,
        new JsonSerializerOptions
        {
            NumberHandling = JsonNumberHandling.AllowReadingFromString
        });