How to Get and send JSON with HttpClient in C#
By FoxLearn 3/6/2025 8:50:07 AM 23
using System.Net.Http.Json; // Fetch JSON var user = await httpClient.GetFromJsonAsync<User>($"https://localhost:12345/users/{userId}"); user.Age = 30; // Submit JSON await httpClient.PostAsJsonAsync<User>("https://localhost:12345/users/", user);
Note: If you are using a framework version prior to .NET 5, you need to install the System.Net.Http.Json
package.
These extension methods leverage System.Text.Json
for serialization, simplifying the process of handling JSON data.
To customize the serialization behavior, you can provide a JsonSerializerOptions
object.
Installing the Required Package
For those using versions before .NET 5, make sure to install the System.Net.Http.Json
NuGet package:
Install-Package System.Net.Http.Json
This command is run in the Package Manager Console (View > Other Windows > Package Manager Console).
Customizing JSON Serialization
If you need to customize how your objects are serialized, you can pass a JsonSerializerOptions
object.
For instance, if you want to serialize enum values as their names instead of their underlying numeric values, use the following setup:
using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; var user = new User() { UserName = "john_doe", Status = UserStatus.Active, Age = 30, LastLogin = DateTimeOffset.Now }; var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); options.Converters.Add(new JsonStringEnumConverter()); await httpClient.PostAsJsonAsync<User>("https://localhost:12345/users/", user, options);
This produces the following JSON, where the Status
property uses the enum name instead of its value:
{ "userName": "john_doe", "age": 30, "lastLogin": "2025-02-10T12:34:56.789Z", "status": "Active" }
Using JsonSerializerDefaults.Web
If you don’t provide a JsonSerializerOptions
object, System.Net.Http.Json
uses the JsonSerializerDefaults.Web
settings, which include:
var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, NumberHandling = JsonNumberHandling.AllowReadingFromString };
When creating your own options for customization, include JsonSerializerDefaults.Web
to maintain these default settings.
If you want to use Newtonsoft.Json
instead, you can fetch and deserialize JSON manually.
For example, How to retrieve a user’s data:
using Newtonsoft.Json; var userId = "john_doe"; var response = await httpClient.GetAsync($"https://localhost:12345/users/{userId}"); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); var user = JsonConvert.DeserializeObject<User>(json); Console.WriteLine($"User {user.UserName} is {user.Age} years old and has status {user.Status}.");
This is more verbose compared to the one-liner httpClient.GetFromJsonAsync<User>(url);
.
Serializing an Object with Newtonsoft
To send an object as JSON using Newtonsoft, you can do the following:
using Newtonsoft.Json; var user = new User() { UserName = "john_doe", Status = UserStatus.Active, Age = 30, LastLogin = DateTimeOffset.Now }; var json = JsonConvert.SerializeObject(user); var response = await httpClient.PostAsync("https://localhost:12345/users/", new StringContent(json, Encoding.UTF8, "application/json")); response.EnsureSuccessStatusCode();
Consider using the Newtonsoft extension methods for HttpClient
to streamline your code instead of repeating the manual serialization process.
- How to Get Status Codes with HttpClient in C#
- How to use TimeZoneInfo in C#
- How to Get key with the max value in a dictionary in C#
- How to Deserialize JSON as a stream in C#
- How to use JsonNode in C#
- TimeZoneInfo with current UTC offset in C#
- How to Parser a CSV file in C#
- How to read configuration from appsettings.json in C#