using System.Collections.Specialized;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace EasyDevCore.Remote.HttpAccess
{
///
/// ISerializer implementation that uses System.Text.Json
/// Default serializer used in calls to GetJson, etc.
///
public class TextJsonSerializer : ISerializer
{
private static JsonSerializerOptions _defaultOptions;
private JsonSerializerOptions _options;
private JsonSerializerOptions _serializerOptions => _options ?? _defaultOptions;
///
/// Initializes a new instance of the class.
///
public TextJsonSerializer()
{
if (_defaultOptions == null)
{
_defaultOptions = new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,
WriteIndented = true,
};
_defaultOptions.Converters.Add(new JsonStringEnumConverter());
_defaultOptions.Converters.Add(new JsonDateTimeConverter());
}
}
///
/// Initializes a new instance of the class.
///
/// The options.
public TextJsonSerializer(JsonSerializerOptions options)
{
_options = options;
}
///
/// Serializes the specified object.
///
/// The object.
///
public string Serialize(object obj)
{
return JsonSerializer.Serialize(obj, _serializerOptions);
}
///
/// Serializes the specified object.
///
///
/// The object.
///
public string Serialize(T obj)
{
return JsonSerializer.Serialize(obj, _serializerOptions);
}
///
/// Deserializes the specified s.
///
///
/// The s.
///
public T Deserialize(string s)
{
return JsonSerializer.Deserialize(s, _serializerOptions);
}
///
/// Deserializes the specified stream.
///
///
/// The stream.
///
public T Deserialize(Stream stream)
{
return JsonSerializer.Deserialize(stream, _serializerOptions);
}
///
/// Deserializes the asynchronous.
///
///
/// The stream.
///
public async Task DeserializeAsync(Stream stream)
{
return await JsonSerializer.DeserializeAsync(stream, _serializerOptions).ConfigureAwait(false);
}
}
}