{"record":{"id":"df347d500c9bca87","repo":"JamesNK/Newtonsoft.Json","slug":"unexpected-value-type-when-writing-binary-0","errorCode":null,"errorMessage":"Unexpected value type when writing binary: {0}","messagePattern":"Unexpected value type when writing binary: (.+?)","errorType":"exception","errorClass":"JsonSerializationException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Converters/BinaryConverter.cs","lineNumber":89,"sourceCode":"        private byte[] GetByteArray(object value)\n        {\n#if HAVE_LINQ\n            if (value.GetType().FullName == BinaryTypeName)\n            {\n                EnsureReflectionObject(value.GetType());\n                MiscellaneousUtils.Assert(_reflectionObject != null);\n\n                return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName)!;\n            }\n#endif\n#if HAVE_ADO_NET\n            if (value is SqlBinary binary)\n            {\n                return binary.Value;\n            }\n#endif\n\n            throw new JsonSerializationException(\"Unexpected value type when writing binary: {0}\".FormatWith(CultureInfo.InvariantCulture, value.GetType()));\n        }\n\n#if HAVE_LINQ\n        private static void EnsureReflectionObject(Type t)\n        {\n            if (_reflectionObject == null)\n            {\n                _reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName);\n            }\n        }\n#endif\n\n        /// <summary>\n        /// Reads the JSON representation of the object.\n        /// </summary>\n        /// <param name=\"reader\">The <see cref=\"JsonReader\"/> to read from.</param>\n        /// <param name=\"objectType\">Type of the object.</param>\n        /// <param name=\"existingValue\">The existing value of object being read.</param>","sourceCodeStart":71,"sourceCodeEnd":107,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Converters/BinaryConverter.cs#L71-L107","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Ensure the value being serialized is a byte[] (or SqlBinary / System.Data.Linq.Binary when available).","Remove the BinaryConverter attribute from properties whose type is not a supported binary type.","If you have a different CLR type, write a custom JsonConverter that converts it to a byte[] before delegating to WriteValue.","Confirm the target framework actually includes the System.Data.Linq/ADO.NET assemblies if you rely on those branches."],"exampleFix":"// before: BinaryConverter applied to a Guid property\n[JsonConverter(typeof(BinaryConverter))]\npublic Guid Id { get; set; }\n\n// after: use a Guid converter, or expose the raw bytes\n[JsonIgnore]\npublic Guid Id { get; set; }\n[JsonProperty(\"id\")]\npublic byte[] IdBytes => Id.ToByteArray();","handlingStrategy":"type-guard","validationCode":"object value = GetValue();\nif (value != null && !(value is byte[]) && value.GetType().FullName != \"System.Data.Linq.Binary\" && !(value is System.Data.SqlTypes.SqlBinary))\n    throw new InvalidOperationException($\"BinaryConverter cannot serialize {value.GetType()}\");","typeGuard":"static bool IsSupportedBinary(object v) =>\n    v is byte[]\n    || v is System.Data.SqlTypes.SqlBinary\n    || (v != null && v.GetType().FullName == \"System.Data.Linq.Binary\");","tryCatchPattern":"try { serializer.Serialize(writer, value); }\ncatch (JsonSerializationException ex) when (ex.Message.Contains(\"Unexpected value type when writing binary\"))\n{\n    throw new InvalidOperationException($\"BinaryConverter got an unsupported type\", ex);\n}","preventionTips":["Only attach BinaryConverter to byte[]/SqlBinary/System.Data.Linq.Binary properties.","After refactoring a property type, re-audit converter attributes.","Write a dedicated converter for other binary-like types."],"tags":["serialization","converter","binary","type-mismatch"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}