Home > Software engineering >  Serialize response from post async .NET 6
Serialize response from post async .NET 6

Time:05-14

I am trying to modify the response when serialized. TimeJoined is returned as a string in format hh:mm (GMT _) and I want to modify as a 24h format, in the instance below would be 14:46

public class Person
{
    public string Name { get; set; }
    public string TimeJoined { get; set; } // "12:46 (GMT  2)"
}

public async Task<Person> GetPerson()
{
    var response = await client.PostAsJsonAsync(url, new { id = "aydt344d" });
    return await response.Content.ReadFromJsonAsync<Person>();
}

CodePudding user response:

Have a look at this Custom Json Converter

After that, you can create a JsonSerializerOptions (it can be globally) and pass it to ReadFromJsonAsync as a parameter. done!

however, in the Person class the TimeJoined is string so you will need to use TimeSpan or parse time and reformat it to that you want

CodePudding user response:

The key for 24h is in the following string format:

hh for 12h format
HH for 24h format
z is for time zone

Lets put that together, something like:

string.Format(DateTime.Now.ToString("HH:mm ({0} z)"), "GMT");

To put that in your person object you can do something like:

var person = await response.Content.ReadFromJsonAsync<Person>(); 
person.TimeJoined = string.Format(DateTime.Now.ToString("HH:mm ({0} z)"), "GMT");
return person;

Or take that format and use it in your customer serializer as the other answer mentioned, that way you can use it overall.

Of course, you can also make a static method and re-used it as well.

Testing that will give time format like this:

15:00 (GMT  2)
  • Related