skip to Main Content

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


  1. It’s better to check if you can convert the value directly to int else, you will run into exception.

    public int inspection_id_int()
    {
        if (int.TryParse(inspection_id, out int result))
        {
            return result;
        }
        else
        {
            return -1;
        }
    }
    
    Login or Signup to reply.
  2. 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 the string 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 the change_date field.

    The process would be something like:

    • Get the data from the API as-is
    • Map the data to your app objects
    • Use the objects however you want in your app
    Login or Signup to reply.
  3. You could do the following:

    Create your own converter

    public class MyConverter : JsonConverter<int>
    {
        public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => int.Parse(reader.GetString());
    
        public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) => writer.WriteStringValue(value.ToString());
    }
    

    decorate your class and change property to int

    public class Root
    {
        public string change_date { get; set; }
    
        [JsonConverter(typeof(MyConverter))]
        public int inspection_id { get; set; }
    
        public string insp_unit_id { get; set; }
    }
    

    Then it will work as you expected

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search