Support for the RemObjects.SDK.Types.Binary type in JSON serializers

The RemObjects.SDK.Types.Binary type is based on the MemoryStream, so the most commonly used JSON serializers do not support it out of the box. One will have to provide own converter class to provide support of the Binary class.

The code below uses this class as a sample:

public class TPerson
{
	public Binary Signature { get; set; }
}

Newtonsoft.JSON

Sample

var data = new TPerson
{
	Signature = new RemObjects.SDK.Types.Binary("Some Value")
};

var serializedObject = JsonConvert.SerializeObject(data, Formatting.Indented, new BinaryNewtonsoftJsonConverter());
data = JsonConvert.DeserializeObject<TPerson>(serializedObject, new BinaryNewtonsoftJsonConverter());

Converter:

public class BinaryNewtonsoftJsonConverter : JsonConverter
{
	public override bool CanConvert(Type objectType)
	{
		return typeof(Binary).IsAssignableFrom(objectType);
	}

	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		var bytes = serializer.Deserialize<byte[]>(reader);
		return bytes != null ? new Binary(bytes) : new Binary();
	}

	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
	{
		var bytes = ((Binary)value).ToArray();
		serializer.Serialize(writer, bytes);
	}
}

System.Web.Script.Serialization.JavaScriptSerializer

Sample

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new BinaryJsonSerializerConverter() });
var result2 = serializer.Serialize(new TPerson
{
	Signature = new RemObjects.SDK.Types.Binary("Some Value")
});

Converter

public class BinaryJsonSerializerConverter : JavaScriptConverter
{
	public override IEnumerable<Type> SupportedTypes
	{
		get
		{
			return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(Binary) }));
		}
	}

	public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
	{
		Binary binary = obj as Binary;

		if (binary == null)
		{
			return new Dictionary<string, object>();
		}

		// Create the representation.
		Dictionary<string, object> result = new Dictionary<string, object>();
		result.Add("Data", binary.ToArray());

		return result;
	}

	public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
	{
		if (dictionary == null)
		{
			throw new ArgumentNullException("dictionary");
		}

		if (type != typeof(Binary))
		{
			return null;
		}

		// Create the instance to deserialize into.

		object rawData;
		return dictionary.TryGetValue("Data", out rawData) && (rawData is byte[])
					? new Binary((byte[])rawData)
					: new Binary();
	}
}