{"record":{"id":"49ff079f0ecfe8ec","repo":"JamesNK/Newtonsoft.Json","slug":"can-not-convert-0-to-byte-array","errorCode":null,"errorMessage":"Can not convert {0} to byte array.","messagePattern":"Can not convert (.+?) to byte array\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Linq/JToken.cs","lineNumber":1395,"sourceCode":"            return Convert.ToUInt64(v.Value, CultureInfo.InvariantCulture);\n        }\n\n        /// <summary>\n        /// Performs an explicit conversion from <see cref=\"JToken\"/> to <see cref=\"Byte\"/>[].\n        /// </summary>\n        /// <param name=\"value\">The value.</param>\n        /// <returns>The result of the conversion.</returns>\n        public static explicit operator byte[]?(JToken? value)\n        {\n            if (value == null)\n            {\n                return null;\n            }\n\n            JValue? v = EnsureValue(value);\n            if (v == null || !ValidateToken(v, BytesTypes, false))\n            {\n                throw new ArgumentException(\"Can not convert {0} to byte array.\".FormatWith(CultureInfo.InvariantCulture, GetType(value)));\n            }\n\n            if (v.Value is string)\n            {\n                return Convert.FromBase64String(Convert.ToString(v.Value, CultureInfo.InvariantCulture)!);\n            }\n#if HAVE_BIG_INTEGER\n            if (v.Value is BigInteger integer)\n            {\n                return integer.ToByteArray();\n            }\n#endif\n\n            if (v.Value is byte[] bytes)\n            {\n                return bytes;\n            }\n","sourceCodeStart":1377,"sourceCodeEnd":1413,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Linq/JToken.cs#L1377-L1413","documentation":"Thrown at the FIRST guard in 'operator byte[]?(JToken?)' when ValidateToken fails. Allowed types are BytesTypes ({Bytes, String, Comment, Raw, Integer}) and the overload is nullable (JSON null returns null). ArgumentException {0} is the resolved JTokenType. So this throw means the token resolved to a JValue whose Type is Float, Boolean, Date, Guid, Uri, TimeSpan, Object, Array, or the token is not a JValue (EnsureValue null). A second, separate throw (error 133) covers the post-validation fallthrough.","triggerScenarios":"Calling (byte[])token[\"hash\"] where the resolved JTokenType is Float, Boolean, Date, Guid, Uri, TimeSpan, Object, or Array, or the node is a JObject/JArray/JConstructor. A base64 string, a raw byte[] JValue, a Comment, or an Integer pass this guard (Integer then risks error 133).","commonSituations":"Binary/hash field emitted as a number (Float) or object instead of a base64 string; field changed to a boolean flag; mis-indexing into a child object/array.","solutions":["Ensure the producer emits binary data as a base64 string and index the scalar node.","Guard token[\"hash\"]?.Type is in {Bytes, String, Comment, Raw} before the cast (treat Integer as risky — see error 133).","Use token[\"hash\"]?.Value<byte[]>() which returns null on incompatible shapes.","If the field is genuinely numeric, parse it to bytes yourself rather than relying on the cast."],"exampleFix":"// before\nbyte[] hash = (byte[])payload[\"hash\"]; // throws when hash is a number/object\n\n// after\nbyte[] hash = (payload[\"hash\"]?.Type == JTokenType.String) ? (byte[])payload[\"hash\"]!! : null;","handlingStrategy":"validation","validationCode":"byte[]? hash = (payload[\"hash\"]?.Type == JTokenType.String || payload[\"hash\"]?.Type == JTokenType.Bytes)\n    ? (byte[])payload[\"hash\"]!! : null;","typeGuard":"static bool IsBinaryCompatible(JToken? t) =>\n    t is JValue v && (v.Type == JTokenType.Bytes || v.Type == JTokenType.String);","tryCatchPattern":"byte[]? hash;\ntry { hash = (byte[])payload[\"hash\"]; }\ncatch (ArgumentException) { hash = null; }","preventionTips":["Ensure producers emit binary as base64 strings.","Restrict pre-cast guards to {Bytes, String} (treat Integer as risky — see error 133).","Use token[\"hash\"]?.Value<byte[]>() for non-throwing reads."],"tags":["json","linq-to-json","type-cast","jtoken","byte-array","base64","newtonsoft-json"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}