using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Bson; using System.Globalization; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Converters { /// /// Converts a to and from JSON and BSON. /// public class BsonObjectIdConverter : JsonConverter { /// /// Writes the JSON representation of the object. /// /// The to write to. /// The value. /// The calling serializer. public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { BsonObjectId objectId = (BsonObjectId) value; BsonWriter bsonWriter = writer as BsonWriter; if (bsonWriter != null) { bsonWriter.WriteObjectId(objectId.Value); } else { writer.WriteValue(objectId.Value); } } /// /// Reads the JSON representation of the object. /// /// The to read from. /// Type of the object. /// The existing value of object being read. /// The calling serializer. /// The object value. public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.Bytes) throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); byte[] value = (byte[])reader.Value; return new BsonObjectId(value); } /// /// Determines whether this instance can convert the specified object type. /// /// Type of the object. /// /// true if this instance can convert the specified object type; otherwise, false. /// public override bool CanConvert(Type objectType) { return (objectType == typeof (BsonObjectId)); } } }