{"record":{"id":"e0a62301f18656ed","repo":"JamesNK/Newtonsoft.Json","slug":"expected-bytes-but-got-0","errorCode":null,"errorMessage":"Expected Bytes but got {0}.","messagePattern":"Expected Bytes but got (.+?)\\.","errorType":"exception","errorClass":"JsonSerializationException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs","lineNumber":73,"sourceCode":"            else\n            {\n                writer.WriteValue(objectId.Value);\n            }\n        }\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>\n        /// <param name=\"serializer\">The calling serializer.</param>\n        /// <returns>The object value.</returns>\n        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)\n        {\n            if (reader.TokenType != JsonToken.Bytes)\n            {\n                throw new JsonSerializationException(\"Expected Bytes but got {0}.\".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));\n            }\n\n            byte[] value = (byte[])reader.Value;\n\n            return new BsonObjectId(value);\n        }\n\n        /// <summary>\n        /// Determines whether this instance can convert the specified object type.\n        /// </summary>\n        /// <param name=\"objectType\">Type of the object.</param>\n        /// <returns>\n        /// \t<c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.\n        /// </returns>\n        public override bool CanConvert(Type objectType)\n        {\n            return (objectType == typeof(BsonObjectId));\n        }","sourceCodeStart":55,"sourceCodeEnd":91,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Converters/BsonObjectIdConverter.cs#L55-L91","documentation":"Thrown by BsonObjectIdConverter.ReadJson when the JsonReader's current token is not JsonToken.Bytes while deserializing a BsonObjectId. The converter expects a byte array (12 bytes) token; any other token type triggers this JsonSerializationException. The {0} shows the actual token type received.","triggerScenarios":"Deserializing JSON where a BsonObjectId-typed property maps to a token that is not a byte array, e.g. a JSON string, integer, or object. Because BsonObjectIdConverter is specific to the obsolete BSON support, this typically happens when JSON produced outside the BSON pipeline (e.g. plain JSON with a string OID) is read by a serializer configured with this converter.","commonSituations":"Mixing plain-JSON data with the BSON-specific BsonObjectIdConverter. Receiving an OID as a 24-char hex string from an API but the converter expects raw bytes. Legacy code still referencing the obsolete BsonObjectId/BsonObjectIdConverter after migrating the wire format to JSON.","solutions":["Ensure the token for BsonObjectId properties is JsonToken.Bytes (a 12-byte array).","If your data is a hex string, add a converter that reads the string and produces a BsonObjectId, instead of using BsonObjectIdConverter.","Migrate away from the obsolete BsonObjectId type to the dedicated Newtonsoft.Json.Bson package's ObjectId."],"exampleFix":"// before: API sends OID as hex string, converter expects bytes\n// { \"_id\": \"507f1f77bcf86cd799439011\" }\nsettings.Converters.Add(new BsonObjectIdConverter());\nvar obj = JsonConvert.DeserializeObject<Foo>(json, settings); // throws\n\n// after: custom converter that handles hex strings\nsettings.Converters.Add(new HexStringObjectIdConverter());","handlingStrategy":"validation","validationCode":"if (reader.TokenType != JsonToken.Bytes)\n    throw new JsonSerializationException($\"BsonObjectId expects bytes, got {reader.TokenType}\");","typeGuard":"static bool IsBytesToken(JsonReader r) => r.TokenType == JsonToken.Bytes;","tryCatchPattern":"try { var oid = serializer.Deserialize<BsonObjectId>(reader); }\ncatch (JsonSerializationException ex) when (ex.Message.Contains(\"Expected Bytes\"))\n{\n    throw new InvalidDataException(\"OID field is not a byte array token\", ex);\n}","preventionTips":["Ensure OID values are emitted as byte arrays, not hex strings, when using BsonObjectIdConverter.","For hex-string OIDs, write a dedicated converter instead of reusing BsonObjectIdConverter.","Migrate to the dedicated Newtonsoft.Json.Bson package's ObjectId type."],"tags":["bson","deserialization","converter","objectid","type-mismatch"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}