JamesNK/Newtonsoft.Json · error · JsonSerializationException

Unexpected value type when writing binary: {0}

Error message

Unexpected value type when writing binary: {0}

What it means

Thrown by BinaryConverter.GetByteArray when the value passed to WriteJson is not one of the supported binary types: a byte[], a System.Data.Linq.Binary, or a System.Data.SqlTypes.SqlBinary. The converter serializes binary data as a base64 string; if the runtime type does not match any known binary type it throws this JsonSerializationException.

Source

Thrown at Src/Newtonsoft.Json/Converters/BinaryConverter.cs:89

        private byte[] GetByteArray(object value)
        {
#if HAVE_LINQ
            if (value.GetType().FullName == BinaryTypeName)
            {
                EnsureReflectionObject(value.GetType());
                MiscellaneousUtils.Assert(_reflectionObject != null);

                return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName)!;
            }
#endif
#if HAVE_ADO_NET
            if (value is SqlBinary binary)
            {
                return binary.Value;
            }
#endif

            throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
        }

#if HAVE_LINQ
        private static void EnsureReflectionObject(Type t)
        {
            if (_reflectionObject == null)
            {
                _reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName);
            }
        }
#endif

        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Ensure the value being serialized is a byte[] (or SqlBinary / System.Data.Linq.Binary when available).
  2. Remove the BinaryConverter attribute from properties whose type is not a supported binary type.
  3. If you have a different CLR type, write a custom JsonConverter that converts it to a byte[] before delegating to WriteValue.
  4. Confirm the target framework actually includes the System.Data.Linq/ADO.NET assemblies if you rely on those branches.

Example fix

// before: BinaryConverter applied to a Guid property
[JsonConverter(typeof(BinaryConverter))]
public Guid Id { get; set; }

// after: use a Guid converter, or expose the raw bytes
[JsonIgnore]
public Guid Id { get; set; }
[JsonProperty("id")]
public byte[] IdBytes => Id.ToByteArray();
Defensive patterns

Strategy: type-guard

Validate before calling

object value = GetValue();
if (value != null && !(value is byte[]) && value.GetType().FullName != "System.Data.Linq.Binary" && !(value is System.Data.SqlTypes.SqlBinary))
    throw new InvalidOperationException($"BinaryConverter cannot serialize {value.GetType()}");

Type guard

static bool IsSupportedBinary(object v) =>
    v is byte[]
    || v is System.Data.SqlTypes.SqlBinary
    || (v != null && v.GetType().FullName == "System.Data.Linq.Binary");

Try / catch

try { serializer.Serialize(writer, value); }
catch (JsonSerializationException ex) when (ex.Message.Contains("Unexpected value type when writing binary"))
{
    throw new InvalidOperationException($"BinaryConverter got an unsupported type", ex);
}

Prevention

When it happens

Trigger: Explicitly adding BinaryConverter to the serializer and then serializing an object whose type is none of the supported binary types. Or applying [JsonConverter(typeof(BinaryConverter))] to a property whose declared type is not byte[]/Binary/SqlBinary. Can also occur when a custom contract resolver forces BinaryConverter onto an incompatible type.

Common situations: Applying BinaryConverter to a property of type Guid, string, int array, or a custom struct expecting it to auto-convert. Mismatch between the converter added to Converters and the actual value type after a refactor. Serializing on a target framework where System.Data.Linq is not referenced (HAVE_LINQ undefined) so the Binary branch is compiled out.

Related errors


AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07). Data as JSON: /api/errors/df347d500c9bca87. Report an issue: GitHub.