I would like to serialize all my contract with $type reference using TypeNameHandling.Objects. However when using this flag, all byte arrays (byte[]) are serialized using $value+$type. I still want Base64 encoding but without $type. For example, for the following contract:
class MyClass
{
public byte[] MyBinaryProperty {get;set;}
}
I get:
{
"$type": "MyLib.MyClass, MyAssembly",
"MyBinaryProperty": {
"$type": "System.Byte[], mscorlib",
"$value": "VGVzdGluZw=="
}
}
I want:
{
"$type": "MyLib.MyClass, MyAssembly",
"MyBinaryProperty": "VGVzdGluZw=="
}
Is it possible to serialize all objects via JSON.NET with $type excluding byte arrays? Can I do this without adding any attributes to the contracts (i.e. I want to only alter serializer settings).
One way to fix this would be to use a custom converter for
byte[]
:This way you're overriding how
byte[]
gets serialized and ultimately passing the serializer astring
instead of a byte array.Here's how you'd use it:
Example output:
Example: https://dotnetfiddle.net/iDEPIT