skip to Main Content

I’m having trouble converting a json into a timeSpan in C#, I have different json. Here are a few examples:

{
  ‘seconds’: 60
}
{
  ‘hours’: 11
}
{
  ‘years: 5
}

If you have any ideas I’d be grateful
Thanks

I’m looking to dynamically create timeSpans based on the returned Json.
For example :
As input:

{
  ‘seconds’: 60
}

=> Output:

new TimeSpan( 0, 0, 0, 60, 0 )

2

Answers


  1. Create your own class do deserialize to. Then convert that to a TimeSpan.

    internal class Program
    {
        static void Main(string[] args)
        {
            var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            var json =
                """
                { "seconds": 60, "days": 5 }
                """;
    
            var timeSpan = JsonSerializer.Deserialize<MyTimeSpan>(json, options)?.ToTimeSpan();
        }
    
        public class MyTimeSpan
        {
            public int Seconds { get; set; }
            public int Minutes { get; set; }
            public int Hours { get; set; }
            public int Days { get; set; }
    
            public TimeSpan ToTimeSpan() => new(Days, Hours, Minutes, Seconds);
        }
    }
    
    Login or Signup to reply.
  2. using System;
    using System.Text.Json;
    public class JsonTimeSpanConverter
    {
    public TimeSpan ConvertJsonToTimeSpan(string json)
    {
        var jsonDocument = JsonDocument.Parse(json);
        var root = jsonDocument.RootElement;
    
        int days = root.TryGetProperty("days", out var daysElement) ? daysElement.GetInt32() : 0;
        int hours = root.TryGetProperty("hours", out var hoursElement) ? hoursElement.GetInt32() : 0;
        int minutes = root.TryGetProperty("minutes", out var minutesElement) ? minutesElement.GetInt32() : 0;
        int seconds = root.TryGetProperty("seconds", out var secondsElement) ? secondsElement.GetInt32() : 0;
        int milliseconds = root.TryGetProperty("milliseconds", out var millisecondsElement) ? millisecondsElement.GetInt32() : 0;
    
        return new TimeSpan(days, hours, minutes, seconds, milliseconds);
    }
    }
    

    The JsonTimeSpanConverter class contains a method ConvertJsonToTimeSpan that takes a JSON string as input and extracts the relevant time components (days, hours, minutes, seconds, and milliseconds) to create a TimeSpan object. The code uses the System.Text.Json namespace for parsing JSON data.

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