Created
April 24, 2020 07:10
-
-
Save deepumi/a1e87038da56549627043df901d68255 to your computer and use it in GitHub Desktop.
Json serialized JsonContent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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