30 lines
1.1 KiB
C#
30 lines
1.1 KiB
C#
#nullable enable
|
|
|
|
using System;
|
|
using System.Text;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace ShrinkNetwork
|
|
{
|
|
public sealed class ShrinkJsonNetworkSerializer : IShrinkNetworkSerializer
|
|
{
|
|
private static readonly JsonSerializerSettings Settings = new()
|
|
{
|
|
NullValueHandling = NullValueHandling.Ignore,
|
|
DefaultValueHandling = DefaultValueHandling.Include,
|
|
Formatting = Formatting.None
|
|
};
|
|
|
|
public byte[] Serialize(object value)
|
|
=> Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value, Settings));
|
|
|
|
public object Deserialize(byte[] payload, Type type)
|
|
=> JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload), type, Settings)
|
|
?? throw new JsonSerializationException($"Failed to deserialize payload into {type.FullName}.");
|
|
|
|
public T Deserialize<T>(byte[] payload)
|
|
=> JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(payload), Settings)
|
|
?? throw new JsonSerializationException($"Failed to deserialize payload into {typeof(T).FullName}.");
|
|
}
|
|
}
|