How to Get and send JSON using HttpClient in C#

By FoxLearn 1/22/2025 3:14:56 AM   4
Handling JSON data in C# is an essential part of modern web development, and HttpClient provides a straightforward way to interact with APIs that return or require JSON.

Starting with .NET 5, the System.Net.Http.Json namespace offers helpful extension methods like GetFromJsonAsync() and PostAsJsonAsync() to simplify sending and receiving JSON data.

Sending and Receiving JSON with HttpClient

The GetFromJsonAsync() and PostAsJsonAsync() methods make it easy to handle JSON data. These methods are part of System.Net.Http.Json and simplify making HTTP requests that involve JSON.

Here’s a simple example of fetching and sending JSON data using HttpClient. Assume we are working with a service that manages information about books.

using System.Net.Http.Json;

// Fetch JSON data
var book = await httpClient.GetFromJsonAsync<Book>($"https://localhost:5001/books/{bookId}");

// Update the book data
book.Price = 19.99;

// Send updated book data as JSON
await httpClient.PostAsJsonAsync<Book>("https://localhost:5001/books/", book);

If you're using .NET Core 3.x or earlier, you’ll need to install the System.Net.Http.Json package:

Install-Package System.Net.Http.Json

These extension methods use System.Text.Json for serialization by default, which helps to reduce the need for manual serialization code.

Customizing JSON Serialization

By default, System.Text.Json uses standard serialization settings. However, you can customize how the JSON is handled by providing a JsonSerializerOptions object.

For example, let’s say we want to serialize an enum as a string instead of its numeric value.

Imagine our Book class has a Genre property which is an enum. By default, System.Text.Json would serialize this enum as an integer, but we want it serialized as a string for better readability.

using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;

// Define a Book object
var book = new Book()
{
    Title = "Learn C#",
    Genre = BookGenre.ScienceFiction,
    Price = 29.99m,
    PublishedDate = DateTimeOffset.Now
};

// Define custom JSON options
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
options.Converters.Add(new JsonStringEnumConverter());

// Send the book as JSON with custom options
await httpClient.PostAsJsonAsync<Book>("https://localhost:5001/books/", book, options);

The JSON will be serialized as follows, with the Genre property now using the string value "ScienceFiction" instead of the numeric representation:

{
    "title": "Learn C#",
    "price": 29.99,
    "publishedDate": "2025-01-22T14:50:00.1234567-05:00",
    "genre": "ScienceFiction"
}

Default Serialization Behavior

If you don’t provide custom options, System.Net.Http.Json uses sensible defaults tailored for web applications. This includes:

  • Case-insensitive property matching
  • Camel-case property naming (e.g., BookTitle becomes bookTitle)
  • Number handling that allows reading numeric strings

These defaults are set via JsonSerializerDefaults.Web, and you can create custom JsonSerializerOptions based on this default behavior.

var options = new JsonSerializerOptions()
{
    PropertyNameCaseInsensitive = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    NumberHandling = JsonNumberHandling.AllowReadingFromString
};

What if You Want to Use Newtonsoft.Json?

While System.Text.Json is the default for JSON handling, some developers may prefer using Newtonsoft.Json, especially if their project already relies on it. Here’s how to manually fetch and serialize JSON using Newtonsoft.Json.

Deserializing JSON with Newtonsoft.Json

Suppose you want to use Newtonsoft.Json for deserialization.

using Newtonsoft.Json;

// Fetch the JSON manually
var bookId = 123;
var response = await httpClient.GetAsync($"https://localhost:5001/books/{bookId}");
response.EnsureSuccessStatusCode();

// Deserialize the JSON response
var json = await response.Content.ReadAsStringAsync();
var book = JsonConvert.DeserializeObject<Book>(json);

Console.WriteLine($"Book: {book.Title} - {book.Price}");

Serializing JSON with Newtonsoft.Json

If you want to send the Book object using Newtonsoft.Json, you can serialize it manually and send it with HttpClient like this:

using Newtonsoft.Json;

// Create a Book object
var book = new Book()
{
    Title = "Advanced C#",
    Genre = BookGenre.Technical,
    Price = 49.99,
    PublishedDate = DateTimeOffset.Now
};

// Serialize the book object to JSON
var json = JsonConvert.SerializeObject(book);

// Send the JSON via HttpClient
var response = await httpClient.PostAsync("https://localhost:5001/books/", 
    new StringContent(json, Encoding.UTF8, "application/json"));

response.EnsureSuccessStatusCode();

Using HttpClient with System.Net.Http.Json makes handling JSON data straightforward and efficient in C#. The GetFromJsonAsync() and PostAsJsonAsync() methods help you simplify the process of sending and receiving JSON data.