Skip to content

Instantly share code, notes, and snippets.

@pictos
Created July 10, 2022 00:33
Show Gist options
  • Save pictos/5ffc47235c78754aa1e3711e7aced079 to your computer and use it in GitHub Desktop.
Save pictos/5ffc47235c78754aa1e3711e7aced079 to your computer and use it in GitHub Desktop.
class BlaP
{
public static async Task<T> FromJsonHttpContent<T>(HttpContent httpContent)
{
Stream stream = null;
try
{
stream = await httpContent.ReadAsStreamAsync();
var res = DeserializeJsonFromsStream<T>(stream);
return res;
}
catch (Exception e)
{
var res = await httpContent.ReadAsStringAsync().ConfigureAwait(false);
JsonErrorHandler?.Invoke(e, res);
throw;
}
finally
{
stream?.Dispose();
}
}
private static T DeserializeJsonFromsStream<T>(Stream stream)
{
using (var sr = new StreamReader(stream))
using (var jtr = new JsonTextReader(sr))
{
var js = new JsonSerializer()
{
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore
};
var result = js.Deserialize<T>(jtr);
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment