JSON¶
JSON is the default serialization format in TypedRest.
Newtonsoft.Json (Default)
The default serializer uses Newtonsoft.Json with the following settings:
- Camel-case property naming
- String enums with camel-case naming
- Null values are not serialized
- Automatic type name handling
var endpoint = new EntryEndpoint(new Uri("http://example.com/"));
// Uses NewtonsoftJsonSerializer by default
To customize the serializer settings:
var endpoint = new EntryEndpoint(
new Uri("http://example.com/"),
serializer: new NewtonsoftJsonSerializer
{
SerializerSettings =
{
DateFormatString = "yyyy-MM-dd"
}
});
System.Text.Json
You can also use the System.Text.Json serializer with the TypedRest.SystemTextJson NuGet package:
Note
The TypedRest.SystemTextJson package version should match your main TypedRest package version. Both packages follow the same versioning scheme.
Default settings:
- Web defaults (camel-case property naming)
- Null values are not serialized when writing
Basic usage:
var endpoint = new EntryEndpoint(
new Uri("http://example.com/"),
serializer: new SystemTextJsonSerializer());
To customize the serializer options:
var endpoint = new EntryEndpoint(
new Uri("http://example.com/"),
serializer: new SystemTextJsonSerializer
{
Options =
{
WriteIndented = true,
Converters = {new JsonStringEnumConverter() }
}
});
TypeScript uses the native JSON.stringify() and JSON.parse() methods:
const endpoint = new EntryEndpoint(new URL("http://example.com/"));
// Uses JsonSerializer by default
Custom serializers
You can implement the Serializer interface for custom serialization:
import { Serializer } from "typedrest";
class MySerializer implements Serializer {
readonly supportedMediaTypes = ["application/json"];
serialize<T>(entity: T): string {
// Custom serialization logic
return JSON.stringify(entity);
}
deserialize<T>(text: string): T {
// Custom deserialization logic
return JSON.parse(text) as T;
}
}
const endpoint = new EntryEndpoint(
new URL("http://example.com/"),
new MySerializer());