Skip to content

Instantly share code, notes, and snippets.

@deepumi
Created April 24, 2020 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepumi/a1e87038da56549627043df901d68255 to your computer and use it in GitHub Desktop.
Save deepumi/a1e87038da56549627043df901d68255 to your computer and use it in GitHub Desktop.
Json serialized JsonContent
public sealed class JsonContent : StreamContent
{
private static MediaTypeHeaderValue JsonMediaType => new MediaTypeHeaderValue("application/json");
public JsonContent(Stream stream) : base(stream)
{
Headers.ContentType = JsonMediaType;
}
public static JsonContent Create(object value)
{
var stream = new MemoryStream();
using (var sw = new StreamWriter(stream, Encoding.UTF8, 1024, true))
using (var jtw = new JsonTextWriter(sw) { Formatting = Formatting.None })
{
var serializer = new JsonSerializer();
serializer.Serialize(jtw, value);
jtw.Flush();
}
stream.Seek(0, SeekOrigin.Begin);
return new JsonContent(stream);
}
}
static void Main()
{
var user = new User{FirstName = "Deepu", LastName = "Madhusoodanan"};
using var message = new HttpRequestMessage(HttpMethod.Post, "");
message.Content = JsonContent.Create(user);
....
}
public class User
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment