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

Remarks

The formatter also reads application/problem+json, the problem details format of RFC 9457 for error responses, and advertises it in the Accept header. It reads any other media type with the +json structured syntax suffix, which RFC 6839 permits for media types whose representation follows application/json, such as application/vnd.example+json, but does not advertise it. It writes application/json only.

The client reads a response with the first formatter in HttpRestClient.ContentFormatters that can read it, so a formatter for a specific +json media 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.

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 null for 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

mediaType string
The media type of the content, without parameters.

Returns

bool
true if mediaType is one of the HttpContentFormatter.ReadableMediaTypes or has the +json structured syntax suffix; otherwise, false.

CreateContent(object, string)

Creates JSON content that carries the specified payload.
protected override HttpContent CreateContent(object payload, string mediaType)

Parameters

payload object
The object to write.
mediaType string
The media type of the content to create.

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

content HttpContent
The HttpContent to read.
modelType Type
The type of the object to read.
cancellationToken CancellationToken
A token for canceling the operation.

Returns

Task<object>
A task that resolves to the object read from content.

Remarks

The content is decoded with the character set of its Content-Type header, or as UTF-8 if it has none.