C# - How to send an object as JSON using the HttpClient

In C# You can easily send an object as JSON with a couple of lines of code. In the below we have an object with a string property called SomeProperty and it has the value "someValue":

var myObject = new SomeObject
{
   SomeProperty = "someValue"
};

In order to send this as JSON we first have to serialize it into a string that we can send as the body of the request. There are two common ways to do this in C#, one is using the JavascriptSerializer, the other is to use JsonConvert from Newtonsoft. Both are included in the below example and both give the same result. After this we can wrap this in a StringContent object and provide the encoding "UTF8" and content type "application/json". After this we can use a standard put or post method from the HttpClient to send this JSON:

var objAsJson = new JavaScriptSerializer().Serialize(myObject);
//var objAsJson = JsonConvert.SerializeObject(myObject);
var content = new StringContent(objAsJson, Encoding.UTF8, "application/json");
var _httpClient = new HttpClient();
var result = await _httpClient.PutAsync("http://someDomain.com/someUrl", content); 
//or PostAsync for POST

That is all there is to it. Using the above you can put or post an object as JSON using the HttpClient.

Please let me know in the comments down below if you know a better way or if you have any other comments to the above!