Class JsonSerializer
Provides JSON serialization and deserialization using System.Text.Json with custom converters for Vonage types.
public class JsonSerializer : IJsonSerializer
- Inheritance
-
JsonSerializer
- Implements
- Inherited Members
Examples
var serializer = new JsonSerializer();
// Serialize an object
var json = serializer.SerializeObject(new { Name = "Test", Value = 123 });
// Deserialize with result handling
var result = serializer.DeserializeObject<MyType>(json);
result.Match(
success => Console.WriteLine($"Parsed: {success}"),
failure => Console.WriteLine($"Failed: {failure.GetFailureMessage()}")
);
Remarks
Pre-configured with camelCase naming, relaxed JSON escaping, and null value handling.
Includes converters for PhoneNumber, MailAddress, and enum types.
Constructors
JsonSerializer()
Initializes a new instance of the JsonSerializer class with default settings.
public JsonSerializer()
JsonSerializer(JsonNamingPolicy)
Constructor with specific naming policy.
public JsonSerializer(JsonNamingPolicy namingPolicy)
Parameters
namingPolicyJsonNamingPolicyThe naming policy.
JsonSerializer(JsonSerializerOptions)
Initializes a new instance of the JsonSerializer class with custom options.
public JsonSerializer(JsonSerializerOptions options)
Parameters
optionsJsonSerializerOptionsThe JSON serializer options to use.
Methods
DeserializeObject<T>(string)
Deserializes a JSON string to the specified type.
public Result<T> DeserializeObject<T>(string serializedValue)
Parameters
serializedValuestringThe JSON string to deserialize.
Returns
- Result<T>
A Result<T> containing the deserialized object on success, or a DeserializationFailure on failure.
Type Parameters
TThe target type to deserialize to.
Examples
var result = serializer.DeserializeObject<User>("{\"name\":\"John\"}");
result.Match(
user => Console.WriteLine(user.Name),
failure => Console.WriteLine("Deserialization failed")
);
SerializeObject<T>(T)
Serializes an object to a JSON string.
public string SerializeObject<T>(T value)
Parameters
valueTThe object to serialize.
Returns
- string
The JSON string representation of the object.
Type Parameters
TThe type of the object to serialize.
Examples
var json = serializer.SerializeObject(new User { Name = "John" });
WithConverter(JsonConverter)
Adds a custom JSON converter to this serializer instance.
public JsonSerializer WithConverter(JsonConverter converter)
Parameters
converterJsonConverterThe JSON converter to add.
Returns
- JsonSerializer
This serializer instance for method chaining.
Examples
var serializer = new JsonSerializer()
.WithConverter(new CustomTypeConverter());