. NET type and JSON mapping relationship

Source: Internet
Author: User

First of all, thank you for your support and attention. This chapter focuses on how. NET types and JSON are mapped. We know that there are basically three types in JSON: value types, arrays, and objects. The types in. NET are much more. How do they map?

In general, Json.NET converts the basic types in. NET (int,float,string, etc.) to JSON values, arrays and collections to JSON arrays, and other transformations to JSON objects.

1. Basic type:

2. Complex Type:

3. Note 3.1 Arrays and collections

If you customize a class that implements arrays and collections and adds its own properties to the class, I'm sorry that when serializing, the property is not serialized. For example, I have defined the following collections:

   Public class myarray:arraylist    {        publicstringgetset;}    }

Instantiate the class and serialize it

New " MyArray "  }; Ma. ADD (1); Ma. ADD (2); Ma. ADD (3string json = jsonconvert.serializeobject (MA); Console.WriteLine (JSON);

Effect:

If I wanted to serialize the array as an object, could it be? The answer is YES!
Just precede the defined array class with the attribute "Jsonobject", and of course introduce the namespace "Newtonsoft.json" first.

      [Jsonobject]    publicclass  myarray:arraylist    {        public  stringgetset;}    }

Results:

Yes, you will find that the results do not have the values we added, and there are a lot of other values that we do not define, because the values we add are stored in a private array in ArrayList, and by default, Json.NET is simply serializing the public member. The extra value is the attribute in the inherited interface.

3.2 Dictionary Types

The dictionary type (dictionary,idictionary,hashtable, etc.) is serialized as an object in the form of Key/value, and the extra attributes are not serialized. There is no longer a detailed talk.

3.3Dynamic Type

In. Net4.0, there are basically two uses of dynamic.
One is used as an attribute, in which case serialization is based on the actual type.
The second use is to inherit the IDynamicMetaObjectProvider interface or DynamicObject base class, for example. NET is built in the class ExpandoObject, the relationship between the three is: Expandoobject,dynamicobject inherited IDynamicMetaObjectProvider. In this case, Only the properties of the returned members of Dynamicmetaobject.getdynamicmembernames are serialized.

First create a new class that inherits the base class DynamicObject

   Public classMydynamic:dynamicobject {//used to store dynamically added variables and values        Privatedictionary<string,Object> members =Newdictionary<string,Object>(); /// <summary>        ///get all the dynamic member names/// </summary>        /// <returns>Dynamic member Names</returns>         Public Overrideienumerable<string>Getdynamicmembernames () {returnMembers .        Keys; }        /// <summary>        ///sets the dynamic member name, which is the method that is set when an assignment statement occurs///For example: dynamic dy = new mydynamic (); ///dy.        Name = "Jack"; /// </summary>        /// <param name= "Binder" >for dynamic setup Operations</param>        /// <param name= "value" >pre-set values</param>        /// <returns></returns>         Public Override BOOLTrysetmember (SetMemberBinder Binder,Objectvalue) {            if(!Members . ContainsKey (binder. Name) {members. ADD (binder.            Name, value); }            ElseMembers[binder. Name]=value; return true; }        /// <summary>        ///get the value of a dynamic member by name///For example: dynamic dy = new mydynamic (); ///var name = dy.        Name; /// </summary>        /// <param name= "Binder" >user dynamic Get operations</param>        /// <param name= "Result" >The object to which the obtained value is assigned</param>        /// <returns></returns>         Public Override BOOLTrygetmember (GetMemberBinder binder, out Objectresult) {            if(members. ContainsKey (binder. Name) {result=Members[binder.                Name]; return true; }            Else                return Base. Trygetmember (Binder, outresult); }        /// <summary>        ///if the member's type is a delegate, it is called/// </summary>        /// <param name= "Binder" >user Dynamic Delegate Operation</param>        /// <param name= "args" >parameters for delegate invocation</param>        /// <param name= "Result" >results returned by delegate invocation</param>        /// <returns></returns>         Public Override BOOLTryinvokemember (Invokememberbinder Binder,Object[] args, out Objectresult) {            if(members. ContainsKey (binder. Name) && Members[binder. Name] isDelegate) {Result= (Members[binder. Name] asDelegate).                DynamicInvoke (args); return true; }            Else            {                return Base. Tryinvokemember (binder, args, outresult); }        }    }

In the main program, do the following:

            New Mydynamic (); // A variable must be declared with dynamic, not mydynamic, or it will not be a dynamic type.               "Jack";            Action<stringnew action<string> ((value) = = { Console.WriteLine (value); });             = output;            Console.WriteLine (Jsonconvert.serializeobject (MD));            Md. Output (Md. Name);

Results:

Yes, the delegate type is also serialized, which is not what we want, is there a way to exclude it? The answer is in the Getdynamicmembernames method, by default we return all keys, as long as we add a certain limit. The code after the modification

         Public Override ienumerable<string> getdynamicmembernames ()        {            foreach (string inch Members . Keys)                (if is Delegate))                    yieldreturn key;            }        }

The result of this operation:

 ok! What's the problem, please tell me in time! Learn together!

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.