这个是个转换的工具类,主要目的是把C#中的ObjectId类转换成Json格式,Json抓换成Mongo的ObjectId,相当于是个序列化反序列化的过程。在以后的接收和发送数据的时候需要用到。
代码:
using MongoDB.Bson; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Servers.Core { //MongoDB的ObjectId 2 Json转换 public class YFObjectIdConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(ObjectId); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.String) { throw new Exception(string.Format("Unexpected token parsring ObjectId. Expected String,got{0}", reader.TokenType)); } string value = (string)reader.Value; return String.IsNullOrEmpty(value) ? ObjectId.Empty : new ObjectId(value); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is ObjectId) { ObjectId objectId = (ObjectId)value; writer.WriteValue(objectId != ObjectId.Empty ? objectId.ToString() : string.Empty); } else { throw new Exception("Expected ObjectId value."); } } } }