標籤:mvc objectid objectid序列化 objectid還原序列化 mvc mongodb
前面有寫使用自己的mvc 序列化工具即jsonNetResult。我這裡結合之前寫的jsonNetResult來做一個Json序列化工具,並且序列化ObjectId成一個字串。具體代碼如下
using System;using System.IO;using System.Text;using System.Web.Mvc;using Aft.Build.Common;using Newtonsoft.Json;using Newtonsoft.Json.Serialization;namespace Aft.Build.MvcWeb.Common{ public class JsonNetResult : JsonResult { public JsonNetResult() { Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Error }; } public JsonNetResult(object data, JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet, string contentType = null, Encoding contentEncoding = null) { Data = data; JsonRequestBehavior = behavior; ContentEncoding = contentEncoding; ContentType = contentType; } private JsonSerializerSettings _settings; public JsonSerializerSettings Settings { get { _settings = _settings ?? new JsonSerializerSettings(); _settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); _settings.Converters.Add(new ObjectIdConverter()); return _settings; } private set { _settings = value; } } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("JSON GET is not allowed"); var response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (Data == null) return; var scriptSerializer = JsonSerializer.Create(Settings); using (var sw = new StringWriter()) { scriptSerializer.Serialize(sw, Data); response.Write(sw.ToString()); } } }}
在jsonnetresult添加一行代碼:
_settings.Converters.Add(new ObjectIdConverter());
我們的ObjectIdConverter具體實現如下:
using System;using MongoDB.Bson;using Newtonsoft.Json;namespace Aft.Build.Common{ public class ObjectIdConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { ObjectId result; ObjectId.TryParse(reader.Value as string, out result); return result; } public override bool CanConvert(Type objectType) { return typeof(ObjectId).IsAssignableFrom(objectType); } }}
這樣JsonNetResult就具備可以序列化ObjectId類型的資料了。當然其他有特殊需要序列的話的東西實現方式類同。
序列化完成了,接下來是還原序列化,如果不經處理Objectid字串是沒有辦法反序列ObjectId對象的會變成Objectid.empt(即全是零0),或者是使用字串來接收,但是這不是我們希望看到的。
我們使用mvc ModelBinder 來實現ObjectId對象的還原序列化
具體代碼如下:
添加引用
using System;using System.Web.Mvc;using MongoDB.Bson;
代碼實現:
public class ObjectIdModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(ObjectId)) { return ObjectId.Empty; } var val = bindingContext.ValueProvider.GetValue( bindingContext.ModelName); if (val == null) { return ObjectId.Empty; } var value = val.AttemptedValue; if (value == null) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type"); return ObjectId.Empty; } ObjectId result; if (ObjectId.TryParse(value, out result)) { return result; } return ObjectId.Empty; } } public class ObjectIdProvider : IModelBinderProvider { public IModelBinder GetBinder(Type modelType) { if (modelType == typeof(ObjectId) || modelType == typeof(ObjectId?)) { return new ObjectIdModelBinder(); } return null; } }
全域註冊,在Global.asax檔案Application_Start方法中添加如下代碼:
ModelBinderProviders.BinderProviders.Add(new ObjectIdProvider());
這樣ObjectId還原序列化就做好了,是不是很簡單,呵呵。