JsonFormatter Class
- Namespace
- Kampute.HttpClient.Json
- Assembly
- Kampute.HttpClient.Json.dll
Definition
Reads and writes
application/json content with System.Text.Json.public sealed class JsonFormatter : HttpContentFormatter- Inheritance
- object
- HttpContentFormatter
- JsonFormatter
Remarks
Constructors
JsonFormatter()
Initializes a new instance of the JsonFormatter class.
public JsonFormatter()Properties
Options
Gets or sets the JSON serializer options.
public JsonSerializerOptions Options { get; set; }Property Value
- JsonSerializerOptions
- The options used to read responses and write payloads, or
nullfor the defaults of JsonSerializer.
Methods
CanReadMediaType(string)
Determines whether this formatter can read content of the specified media type.
protected override bool CanReadMediaType(string mediaType)Parameters
mediaTypestring- The media type of the content, without parameters.
Returns
- bool
trueifmediaTypeis one of the HttpContentFormatter.ReadableMediaTypes or has the+jsonstructured syntax suffix; otherwise,false.
CreateContent(object, string)
Creates JSON content that carries the specified payload.
protected override HttpContent CreateContent(object payload, string mediaType)Parameters
Returns
- HttpContent
- A JsonContent with the Options of this formatter.
ReadContentAsync(HttpContent, Type, CancellationToken)
Asynchronously reads an object of the specified type from JSON content.
protected override Task<object> ReadContentAsync(HttpContent content, Type modelType, CancellationToken cancellationToken)Parameters
contentHttpContent- The HttpContent to read.
modelTypeType- The type of the object to read.
cancellationTokenCancellationToken- A token for canceling the operation.
Returns
Remarks
The content is decoded with the character set of its
Content-Type header, or as UTF-8 if it has none.

The formatter also reads
application/problem+json, the problem details format of RFC 9457 for error responses, and advertises it in theAcceptheader. It reads any other media type with the+jsonstructured syntax suffix, which RFC 6839 permits for media types whose representation followsapplication/json, such asapplication/vnd.example+json, but does not advertise it. It writesapplication/jsononly.The client reads a response with the first formatter in HttpRestClient.ContentFormatters that can read it, so a formatter for a specific
+jsonmedia type takes over that type only when it is added before this one.Register the formatter with UseJson(this HttpRestClient, JsonSerializerOptions). Its Options apply both to the responses it reads and to the payloads it writes. Change them before the client sends requests, because a registered formatter is shared by all requests of the client.