Ybsoftwarefactory code generation plug-in [20]: serialization of dynamicobject

Source: Internet
Author: User

Dynamicobject is. A class that is supported since net 4.0, but the class is in. net 4.0 is not marked as [serializable] attribute, but in. net 4.5 is marked with [serializable] attribute. It should be noted that, if you need to perform XML serialization and other operations (for example, in WCF), it will be deployed to the uninstalled directory. in the. NET 4.5 environment, errors are usually reported and an exception is reported, regardless of the target platform you use during compilation. is. Net 4.0 or. net 4.5. Normally, this error is normal on the development machine where the. NET 4.5 environment is installed. Even if the project you created is based on. NET 4.0, the. NET 4.5 library is actually called. Therefore, exercise caution when dynamicobject is used and serialization is required (especially in the WCF environment) unless you implement custom serialization operations. This reminds developers to pay attention to this issue. Otherwise, you will be overwhelmed (such as Windows Server 4.5 and other environments) when you are officially deployed to an environment where. NET 2003 cannot be installed ).

In the previous article: "object classes work with database table fields to expand attributes", this article describes how to use dynamicobject to expand attributes, however, the serialization results of this class in JSON serialization under MVC are not friendly. This article mainly discusses how to serialize dynamicobject inheritance classes in JSON.

To serialize dynamicobject objects in JSON format, you only need to implement the idictionary <string, Object> interface in the inheritance class of dynamicobject, because javascriptserializer and JSON. net supports the serialization of idictionary <string, Object>. This interface manages the attributes and values of dynamicobject objects. The extensionobject class mentioned above inherits from the dynamicobject class and implements the idynamicmetaobjectprovider and idictionary <string, Object> interfaces.

The implementation method of idictionary <string, Object> system. Collections. ienumerable. getenumerator () is used to obtain the attribute name to be serialized in the serialization crioptserializer serialization of the original ecosystem in MVC.

JSON. Net calls the implementation method ienumerable <keyvaluepair <string, Object>. getenumerator () of idictionary <string, Object> to obtain attributes and their values.

However, the biggest difference between the two is that using javascrioptserializer to serialize data to the following JSON format:

{"Key": "code", "value": "4" },{ "key": "ID", "value": "d8ea26b06d9d4c7e85ccc43da71320ac "}, {"key": "longname", "value": "null" },{ "key": "fcode", "value": "/51/5100/4 "}, {"key": "nodelevel", "value": "3 "}}

JSON. net serialization: {"ID": "d8ea26b06d9d4c7e85ccc43da71320ac", "code": "4", "longname": NULL, "fcode": "/51/5100/4 ", "nodelevel": 3}

There is no doubt that using JSON. Net for serialization is more in line with actual conditions and needs, and the speed is faster. Of course, in webapi, JSON is already used. net, as the default serialization component, does not have the above problem. Therefore, this article mainly focuses on the JSON of dynamicobject in MVC. net serialization implementation.

1. JSON. Net serialization in MVC

1. Implement custom actionresult and inherit from the jsonresult class. The Code is as follows:

using System;using System.Web.Mvc;using Newtonsoft.Json;using Newtonsoft.Json.Converters;namespace YbRapidSolution.Presenter.JsonNet{    public class JsonNetResult : JsonResult    {        public JsonSerializerSettings SerializerSettings { get; set; }        public JsonNetResult()            : base()        {            // create serializer settings            this.SerializerSettings = new JsonSerializerSettings();            // 阻止属性循环引用的情况下出现的异常            this.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;            // setup default serializer settings            this.SerializerSettings.Converters.Add(new IsoDateTimeConverter());        }        public JsonNetResult(string contentType)            : this()        {            ContentType = contentType;        }        public JsonNetResult(string contentType, System.Text.Encoding contentEncoding)            : this(contentType)        {            ContentEncoding = contentEncoding;        }        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 request GET not allowed");            }            // 获取当前 http context response            var response = context.HttpContext.Response;            // 设置 content type            response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";            // 设置 encoding            if (ContentEncoding != null)                response.ContentEncoding = this.ContentEncoding;            if (Data != null)            {                // 使用 JSON.Net 把对象序列化为 JSON                 string jsonText = JsonConvert.SerializeObject(this.Data, Formatting.Indented, this.SerializerSettings);                // write the response                response.Write(jsonText);            }        }    }}

2. method extension for Controller

using System.Dynamic;using System.Web.Mvc;using YbRapidSolution.Presenter.Controllers;namespace YbRapidSolution.Presenter.JsonNet{    public static class JsonNetControllerExtensions    {        public static JsonNetResult JsonNet(this Controller controller, object data)        {            return new JsonNetResult() { Data = data };        }        public static JsonNetResult JsonNet(this Controller controller, object data,string contentType)        {            return new JsonNetResult(contentType) { Data = data };        }    }}

3. the demo of the call method is as follows:

/// <summary>        /// 查找当前登录用户的当前岗位对本模块所具有的动作权限集合        /// </summary>        /// <param name="orgFId">当前登录用户所使用的岗位(人员成员)的标识全路径</param>        /// <returns></returns>        [AcceptVerbs(HttpVerbs.Post)]        [YbMvcAuthorize(PermissionKeys = PERMISSIONKEY)]        public JsonResult FindAllowActionsFor(string orgFId)        {            try            {                var curMessage = new EasyUIMessage(true, "权限项加载成功");                //查询类型为按钮或右键菜单的动作                var actions = _permissionService                    .FindControlsForOrgByKeyAndOrgFId(PERMISSIONKEY,orgFId);                                curMessage.data = actions;                return this.JsonNet(curMessage);            }            catch (Exception er)            {                var curMessage = new EasyUIMessage(false, string.Format("权限项加载失败:{0}", er.Message));                return this.JsonNet(curMessage);            }        }

Ii. JSON. Net serialization for Web APIs

Because the web API uses JSON. NET as the default JSON serialization implementation framework, you usually need to write the following code in the register of the webapiconfig class for Configuration:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling                = ReferenceLoopHandling.Serialize;config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling                = PreserveReferencesHandling.Objects; 

The permission model provides an extension mechanism for attributes of organizations, users, and roles. For more information, see permission model demo.

Appendix 1: extensionobject source code

Appendix 2: ybsoftwarefactory underlying component help document

In the next chapter, we will share some experience on improving the performance of webapi and MVC.

Ybsoftwarefactory code generation plug-in [20]: serialization of dynamicobject

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.