You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.3 KiB
55 lines
1.3 KiB
using System.Text;
|
|
using System.Text.Json;
|
|
using CoreAgent.WebSocketTransport.Interfaces;
|
|
|
|
namespace CoreAgent.WebSocketTransport.Services;
|
|
|
|
/// <summary>
|
|
/// JSON 消息序列化器
|
|
/// 单一职责:负责消息的序列化和反序列化
|
|
/// </summary>
|
|
public class JsonMessageSerializer : IMessageSerializer
|
|
{
|
|
private readonly JsonSerializerOptions _options;
|
|
|
|
public JsonMessageSerializer(JsonSerializerOptions? options = null)
|
|
{
|
|
_options = options ?? new JsonSerializerOptions
|
|
{
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
WriteIndented = false
|
|
};
|
|
}
|
|
|
|
public byte[] Serialize<T>(T message)
|
|
{
|
|
if (message == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(message));
|
|
}
|
|
|
|
var json = JsonSerializer.Serialize(message, _options);
|
|
return Encoding.UTF8.GetBytes(json);
|
|
}
|
|
|
|
public T? Deserialize<T>(byte[] data)
|
|
{
|
|
if (data == null || data.Length == 0)
|
|
{
|
|
return default;
|
|
}
|
|
|
|
var json = Encoding.UTF8.GetString(data);
|
|
return JsonSerializer.Deserialize<T>(json, _options);
|
|
}
|
|
|
|
public T? Deserialize<T>(string json)
|
|
{
|
|
if (string.IsNullOrEmpty(json))
|
|
{
|
|
return default;
|
|
}
|
|
|
|
return JsonSerializer.Deserialize<T>(json, _options);
|
|
}
|
|
}
|