JSON. Net series tutorial 2. Net ing between types and JSON

Source: Internet
Author: User

Thank you for your support and attention. this chapter mainly introduces. how is the net type mapped to JSON. we know that there are basically three types in JSON: Value Type, array and object. however. net has many types. how are they mapped?

In general, JSON. net will. net basic type (INT, float, String, etc.) to the JSON value, array and set to the JSON array, other converted to the JSON object.

1. Basic types:

2. complex types:

3. Note 3.1 arrays and collections

If you customize the classes that implement arrays and collections and add your own attributes to the classes, sorry, this attribute will not be serialized during serialization. for example, I have defined the following set:

    public class MyArray : ArrayList    {        public string Name { get; set; }    }

Instantiate this class and serialize it

            MyArray ma = new MyArray { Name = "myArray" };            ma.Add(1);            ma.Add(2);            ma.Add(3);            string json = JsonConvert.SerializeObject(ma);            Console.WriteLine(json);

Effect:

If I want to serialize an array as an object, can I? The answer is yes!
You only need to add the "jsonobject" feature before the defined array class. Of course, you must first introduce the namespace "newtonsoft. JSON ".

    [JsonObject]    public class MyArray : ArrayList    {        public string Name { get; set; }    }

Result:

Yes, you will find that the value we added does not exist in the result, and there are many other values that we do not define, this is because the value we added is stored as a private array in the arraylist. By default, JSON. net only serializes public members. the extra value is the property in the inherited interface.

3.2 dictionary type

Dictionary types (Dictionary, idictionary, hashtable, etc.) will be serialized as objects and serialized in the form of key/value. Additional attributes will not be serialized. I will not go into details here.

3.3dynamic type

In. net4.0, dynamic has two usage methods.
One is used as an attribute. In this case, serialization depends on the actual type.
The second method inherits the idynamicmetaobjectprovider interface or the dynamicobject base class, for example. net built-in class expandoobject, the relationship between the three is: expandoobject, dynamicobject inherits idynamicmetaobjectprovider. in this case, only dynamicmetaobject. attributes of the members returned by getdynamicmembernames are serialized.

First, create a class that inherits the base class dynamicobject.

Public class mydynamic: dynamicobject {// used to store dynamically added variables and values private dictionary <string, Object> members = new dictionary <string, Object> (); /// <summary> /// obtain the names of all dynamic members /// </Summary> /// <returns> dynamic member names </returns> Public override ienumerable <string> getdynamicmembernames () {return members. keys;} // <summary> // set the dynamic member name, that is, this method is triggered when a value assignment statement occurs. // For example, dynamic DY = new mydynamic (); /// dy. name = "Jack ";// // </Summary> /// <Param name = "binder"> used for Dynamic Setting Operations </param> /// <Param name = "value"> default value </ param> // <returns> </returns> Public override bool trysetmember (setmemberbinder binder, object value) {If (! Members. containskey (binder. name) {members. add (binder. name, value);} else members [binder. name] = value; return true;} // <summary> // obtain the value of a dynamic member based on the name. // For example, dynamic DY = new mydynamic (); /// var name = Dy. name; /// </Summary> /// <Param name = "binder"> User dynamic acquisition operation </param> /// <Param name = "result"> object To which the value is assigned </param> /// <returns> </returns> Public override bool trygetmember (getmemberbinder binder, out object result) {If (members. containskey (binder. name) {result = members [binder. name]; return true;} else return base. trygetmember (binder, out result);} // <summary> // if the member type is delegate, call it /// </Summary> /// <Param name = "binder"> User dynamic delegate operation </param> /// <Param name = "ARGs"> parameters of the delegate call </param> /// <Param name = "result"> result returned by the delegate call </param> /// <returns> </returns> Public override bool tryinvokemember (invokememberbinder binder, object [] ARGs, out object result) {If (members. containskey (binder. name) & members [binder. name] Is delegate) {result = (members [binder. name] as delegate ). dynamicinvoke (ARGs); Return true;} else {return base. tryinvokemember (binder, argS, out result );}}}

In the main program, do the following:

Dynamic MD = new mydynamic (); // The variable must be declared using dynamic, and mydynamic cannot be used; otherwise, it is not a dynamic type. Md. name = "Jack"; Action <string> output = new action <string> (value) => {console. writeline (value) ;}); Md. output = output; console. writeline (jsonconvert. serializeobject (MD); Md. output (MD. name );

Result:

Yes, the delegate type is also serialized. This is not what we want. Is there a way to exclude it? The answer is in the getdynamicmembernames method. By default, all the keys are returned, as long as we add certain restrictions. The modified code

        public override IEnumerable<string> GetDynamicMemberNames()        {            foreach (string key in members.Keys)            {                if(!(members[key] is Delegate))                    yield return key;            }        }

The running result is as follows:

OK! Please let me know if you have any questions! 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.