Serialize a byte array in JSON.NET without $ type

I would like to serialize my entire contract with a link like $ 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 to:

{
  "$type": "MyLib.MyClass, MyAssembly",
  "MyBinaryProperty": "VGVzdGluZw=="
}

Is it possible to serialize all objects via JSON.NET using $ type, excluding byte arrays? Can I do this without adding any attributes to the contracts (i.e. I only want to change the serializer settings).

+4
source share
1 answer

One way to fix this is to use a custom converter for byte[]:

public class ByteArrayConverter : JsonConverter
{
    public override object ReadJson(
        JsonReader reader,
        Type objectType,
        object existingValue,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(
        JsonWriter writer,
        object value,
        JsonSerializer serializer)
    {
        string base64String = Convert.ToBase64String((byte[])value);

        serializer.Serialize(writer, base64String);
    }    

    public override bool CanRead
    {
        get { return false; }
    }

    public override bool CanConvert(Type t)
    {
        return typeof(byte[]).IsAssignableFrom(t);
    }
}

, , byte[] a string .

:

string serialized = JsonConvert.SerializeObject(mc, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Objects,
    Formatting = Newtonsoft.Json.Formatting.Indented,
    Converters = new[] { new ByteArrayConverter() }
});

:

{
  "$type": "UserQuery+MyClass, query_fajhpy",
  "MyBinaryProperty": "AQIDBA=="
}

: https://dotnetfiddle.net/iDEPIT

+3

All Articles