JavaScriptSerializer serialization and deserialization of JSON: use custom JavaScriptConverter

Source: Internet
Author: User

JSON serialization and deserialization have become essential knowledge for Web development. Currently, criptserializer under System. Web. Script. Serialization is commonly used for processing. Another commonly used and efficient class library is JSON. NET.

When developing small applications, you are reluctant to use JSON. NET because you want to minimize project dependencies. JavaScriptSerializer can basically meet simple requirements, but when an attribute needs to be serialized into another name, it seems powerless. In addition, some attributes may not be serialized under certain conditions. In view of the above business needs, we need to customize a JavaScriptConverter.

Custom use process of JavaScriptConverter:

  • Define a JavaScriptConverter to specify the supported types during the period.
  • Register this converter before calling the serialization method.

Obviously, these two steps are not very troublesome. In ExtJS's TreePanel control, the TreeNode attributes include id and text. If the checked attribute exists, the node selection box is displayed. In C #, checked is a keyword, so it cannot be defined as an attribute. The C # code of TreeNode is as follows:

    public class TreeNode    {        public string id { get; set; }        public string text { get; set; }        public bool? isChecked { get; set; }        public List<TreeNode> children { get; set; }    }

I map the checked attribute to the isChecked field in the class. This field can have three states: null, true, and false. When it is null, this field will not be serialized, the node selection box is not displayed in the foreground.

To implement a TreeNodeJSConverter, the Code is as follows:

    public class TreeNodeJSConverter : JavaScriptConverter    {        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)        {            TreeNode node = new TreeNode();            object value = null;            if (dictionary.TryGetValue("id", out value))                node.id = (string)value;            if (dictionary.TryGetValue("text", out value))                node.text = (string)value;            if (dictionary.TryGetValue("children", out value))            {                if (value != null && value.GetType() == typeof(ArrayList))                {                    var list = (ArrayList)value;                    node.children = new List<TreeNode>();                    foreach (Dictionary<string, object> item in list)                    {                        node.children.Add((TreeNode)this.Deserialize(item, type, serializer));                    }                }                else                {                    node.children = null;                }            }            return node;        }        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)        {            Dictionary<string, object> dic = new Dictionary<string, object>();            var node = obj as TreeNode;            if (node == null)                return null;            if(!string.IsNullOrEmpty(node.id))            dic.Add("id", node.id);            if (!string.IsNullOrEmpty(node.text))            dic.Add("text", node.text);            if (node.isChecked.HasValue)                dic.Add("checked", node.isChecked.Value);            if (node.children != null)            dic.Add("children", node.children);            return dic;        }        public override IEnumerable<Type> SupportedTypes        {            get            {                return new Type[] { typeof(TreeNode) };            }        }    }

Code discussion: the TreeNodeJSConverter class first needs to inherit JavaScriptConverter and then implement its related methods: Deserialize, Serialize, and SupportedTypes, which are deserialization, serialization, and supported types.

In the serialization method Serialize, we need to add the attribute to a dictionary structure to complete the serialization. To serialize the fields, you must determine whether the corresponding values exist.

In the deserialization method Deserialize, the dictionary structure stores the corresponding values. When Values exist, you can assign values to the corresponding fields of TreeNode. The children attribute is troublesome because it is a nested List type, and the Array Structure in JSON is converted to the ArrayList structure. Therefore, we only need to recursively iterate every item in the ArrayList, convert it to TreeNode.

Finally, the SupportedTypes field returns the supported types. The returned TreeNode type is shown here.

 

After the converter is defined, we need to register the converter during serialization:

        public static string SerializeToJson(object obj)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            serializer.RegisterConverters(new JavaScriptConverter[] { new TreeNodeJSConverter() });            return serializer.Serialize(obj);        }        public static T DeserializeJson<T>(string jsonString)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            serializer.RegisterConverters(new JavaScriptConverter[] { new TreeNodeJSConverter() });            return serializer.Deserialize<T>(jsonString);        }

The red part of the code is the place where the converter is registered. It is very convenient to use. The code is pasted out and the source code is no longer provided for download .. Go to bed early!

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.