DynamicObject extension-serialization and deserialization of JSON and DynamicObject, dynamicobjectjson

Source: Internet
Author: User

DynamicObject extension-serialization and deserialization of JSON and DynamicObject, dynamicobjectjson

For a long time, du Niang couldn't find my satisfactory answer, so she had to join the east and west to implement one.

DynamicObject extension-achieves serialization and deserialization of JSON and DynamicObject, which is well tested.

 

View code

Using System; using System. collections; using System. collections. generic; using System. componentModel; using System. dynamic; using System. runtime. compilerServices; using Newtonsoft. json; namespace ConsoleApplication {[Serializable] public class ExtensionDynamicObject: DynamicObject, IDictionary <string, object>, ICloneable, INotifyPropertyChanged {private readonly IDictionary <string, object> _ values = ne W Dictionary <string, object> (); # region IDictionary <String, Object> interface implements public object this [string key] {get {return _ values [key];} set {_ values [key] = value; OnPropertyChanged (key) ;}} public int Count {get {return _ values. count ;}} public bool IsReadOnly {get {return _ values. isReadOnly ;}} public ICollection <string> Keys {get {return _ values. keys ;}} public ICollection <object> Valu Es {get {return _ values. values ;}} public void Add (KeyValuePair <string, object> item) {_ values. add (item);} public void Add (string key, object value) {_ values. add (key, value);} public void Clear () {_ values. clear ();} public bool Contains (KeyValuePair <string, object> item) {return _ values. contains (item);} public bool ContainsKey (string key) {return _ values. containsKey (key);} public void CopyTo (KeyValuePair <string, object> [] array, int arrayIndex) {_ values. copyTo (array, arrayIndex);} public IEnumerator <KeyValuePair <string, object> GetEnumerator () {return _ values. getEnumerator ();} public bool Remove (KeyValuePair <string, object> item) {return _ values. remove (item);} public bool Remove (string key) {return _ values. remove (key);} public bool TryGetValue (string key, out object va Lue) {return _ values. tryGetValue (key, out value);} IEnumerator IEnumerable. getEnumerator () {return _ values. getEnumerator () ;}# endregion # region ICloneable interface implements public object Clone () {var clone = new ExtensionDynamicObject () as IDictionary <string, object>; foreach (var key in _ values. keys) {clone [key] = _ values [key] is ICloneable? (ICloneable) _ values [key]). clone (): _ values [key];} return clone;} # endregion # region INotifyPropertyChanged interface implement public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged ([CallerMemberName] string propertyName = null) {PropertyChanged ?. Invoke (this, new PropertyChangedEventArgs (propertyName ));} # endregion // <summary> // obtain the property value // </summary> // <param name = "propertyName"> </param> // <returns> </returns> public object GetPropertyValue (string propertyName) {if (_ values. containsKey (propertyName) = true) {return _ values [propertyName];} return null ;} /// <summary> /// set the property value /// </summary> /// <param name = "propertyName"> </param >/// <Param name = "value"> </param> public void SetPropertyValue (string propertyName, object value) {if (_ values. containsKey (propertyName) = true) {_ values [propertyName] = value;} else {_ values. add (propertyName, value) ;}/// <summary> /// Method for accessing members of dynamic object attributes, returns the value of the specified property. // </summary> /// <param name = "binder"> </param> /// <param name = "result"> </param> // <returns> </returns> public override bool TryGetMember (GetMemberBinder binder, out object result) {result = GetPropertyValue (binder. Name); return result! = Null;} /// <summary> // method for setting Dynamic Object attribute values. /// </Summary> /// <param name = "binder"> </param> /// <param name = "value"> </param> /// <returns> </returns> public override bool TrySetMember (SetMemberBinder binder, object value) {SetPropertyValue (binder. name, value); return true ;} //// <summary> /// http://blog.csdn.net/hawksoft/article/details/7534332 //// actual code to be executed when a dynamic object dynamic method call is executed //// </summary> //// /<param name = "binder"> </param> /// <param name = "args"> </param> //// <param name =" result "> </param> //// <returns> </returns> // public override bool TryInvokeMember (InvokeMemberBinder binder, object [] args, out object result) // {// var theDelegateObj = GetPropertyValue (binder. name) as DelegateObj; // if (theDelegateObj = null | theDelegateObj. callMethod = null) // {// result = null; // return false; //} // result = theDelegateObj. callMethod (this, args); // return true; //} public override bool TryInvoke (InvokeBinder binder, object [] args, out object result) {return base. tryInvoke (binder, args, out result) ;}} public class ExcelModelDynamicObject: ExtensionDynamicObject {public string Name {get {return this ["Name"]. toString () ;}set {this ["Name"] = value ;}} public string Age {get {return this ["Age"]. toString () ;}set {this ["Age"] = value ;}} class Program {static void Main (string [] args) {dynamic eo = new ExcelModelDynamicObject (); eo. age = 25; eo. name = "Allen"; eo ["Title"] = "Test Dynamic Object"; eo. content = "Hi, Allen. "; string jsonString = JsonConvert. serializeObject (eo); // {"Age": 25, "Name": "Allen", "Title": "Test Dynamic Object", "Content": "Hi, allen. "} dynamic eo2 = JsonConvert. deserializeObject <ExcelModelDynamicObject> (jsonString); string value1 = eo2.Title; // Hello string value2 = eo2.Content; // Hi, Allen. excelModelDynamicObject eo3 = eo2; string value3 = eo3.Age; string value4 = eo3.Name; // very done .}}}

 

Related Article

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.