using System; using System.Globalization; using DPumpHydr.WinFrmUI.WenSkin.Json.Bson; using DPumpHydr.WinFrmUI.WenSkin.Json.Utilities; namespace DPumpHydr.WinFrmUI.WenSkin.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 bsonObjectId = (BsonObjectId)value; BsonWriter bsonWriter = writer as BsonWriter; if (bsonWriter != null) { bsonWriter.WriteObjectId(bsonObjectId.Value); } else { writer.WriteValue(bsonObjectId.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)); } return new BsonObjectId((byte[])reader.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); } } }