using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Server_Dashboard_Socket.Protocol {
///
/// Json serializer class
///
public class JsonMessageProtocol : Protocol {
//The Json serializer and the settings
private static readonly JsonSerializer serializer;
///
/// Settings for the Json Serializer
///
static JsonMessageProtocol() {
//Set the settings
JsonSerializerSettings settings = new JsonSerializerSettings {
Formatting = Formatting.Indented,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
ContractResolver = new DefaultContractResolver {
NamingStrategy = new CamelCaseNamingStrategy {
ProcessDictionaryKeys = false
}
}
};
settings.PreserveReferencesHandling = PreserveReferencesHandling.None;
//Creates the serializer with the settings
serializer = JsonSerializer.Create(settings);
}
//Decode the message, to Json
protected override JObject Decode(byte[] message) => JObject.Parse(Encoding.UTF8.GetString(message));
///
/// Encode the body from Json to bytes
///
/// The message type e.g. object or string
/// The message to send
/// message as byte[]
protected override byte[] EncodeBody(T message) {
var sb = new StringBuilder();
var sw = new StringWriter(sb);
serializer.Serialize(sw, message);
return Encoding.UTF8.GetBytes(sb.ToString());
}
}
}