一、前言
特別不喜歡麻煩的一個人,最近碰到了微信開發。下載下來了一些其他人寫的微信開發“框架”,但是被惡心到了,實現的太臃腫啦。
最不喜歡的就是把微信返回的xml消息在組裝成實體類,所以會比較臃腫,現在都提倡輕量級,所以有什么辦法可以避免大量實體類的存在呢。
當然,還有包裝的比較繁雜,看完官方API后,再看"框架",讓人感覺一頭霧水,不夠清晰、明了。
二、我的實現思路
我的微信SDK(不敢自稱框架),最重要的實現2個目標:
1.輕量級,就是要摒棄實體類,盡量少的申明Entity,減少SDK的體量;
2.簡單、明了,就是SDK類的劃分和官方API保持一致,讓人一看就懂你的用意。
用戶發送請是首先POST到微信服務器的,然后微信服務器在POST到我的服務器,這個接受的消息是xml,我猜測為什么是xml,而不是更輕量級的json,是為了更好的兼容性,畢竟xml更通用一些(說錯了,請指出來)。而我們主動調用微信的一些API時,它返回的是json格式,我靠,要死啊,高大上啊。你們的副總裁張小龍不知道這事嗎?好吧,這樣其實也可以的。
其實,調用微信的工作原理很簡單,沒有必要上來就框架什么的,我相信是個合格的程序員都能做出來。
我們的服務器只需要一個GET,和一個POST就可以和微信通信了,從這一點來看,設計的還是比較人性化的,贊一個。GET用于接通微信服務的校驗,驗證;POST用于接收微信服務器過來的消息,然后將Response組裝好返回即可。
三、上代碼
好了,廢話不多說了。
由于微信服務器Post給我們的是xml消息,返回的是json,所以需要互轉。這樣就存在3種類型的format,這也是大量的框架定義實體類導致框架不夠輕量級的的原因之所在。
實現第一個目標,我主要用到了.net Framework4.0的Dynamic特性,和一個將xml字符串自動轉換成Dynamic Object的DynamicXml.cs類,還有一個將json字符串自動轉換成Dynamic Object的DynamicJson.cs類。
苦苦尋覓,終于讓我找到了我想要的。
1.以下是DynamicXml.cs類,文件頭有原作者的版權信息。

/*-------------------------------------------------------------------------- * https://www.captechconsulting.com/blog/kevin-hazzard/fluent-xml-parsing-using-cs-dynamic-type-part-1 * 博客園網友 夜の魔王 友情借用此代碼,用于微信開發。 * http://m.survivalescaperooms.com/deepleo/*--------------------------------------------------------------------------*/using System;using System.Collections.Generic;using System.Linq;using System.Dynamic;using System.Xml.Linq;using System.Collections;public class DynamicXml : DynamicObject, IEnumerable{ PRivate readonly List<XElement> _elements; public DynamicXml(string text) { var doc = XDocument.Parse(text); _elements = new List<XElement> { doc.Root }; } protected DynamicXml(XElement element) { _elements = new List<XElement> { element }; } protected DynamicXml(IEnumerable<XElement> elements) { _elements = new List<XElement>(elements); } public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; if (binder.Name == "Value") result = _elements[0].Value; else if (binder.Name == "Count") result = _elements.Count; else { var attr = _elements[0].Attribute(XName.Get(binder.Name)); if (attr != null) result = attr; else { var items = _elements.Descendants(XName.Get(binder.Name)); if (items == null || items.Count() == 0) return false; result = new DynamicXml(items); } } return true; } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { int ndx = (int)indexes[0]; result = new DynamicXml(_elements[ndx]); return true; } public IEnumerator GetEnumerator() { foreach (var element in _elements) yield return new DynamicXml(element); }}View Code這個代碼我也沒仔細看,反正能用,沒出過差錯。
2.以下是DynamicJson.cs類,文件頭有原作者的版權信息

/*--------------------------------------------------------------------------* DynamicJson* ver 1.2.0.0 (May. 21th, 2010)** created and maintained by neuecc <ils@neue.cc>* licensed under Microsoft Public License(Ms-PL)* http://neue.cc/* http://dynamicjson.codeplex.com/ * 博客園網友 夜の魔王 友情借用此代碼,用于微信開發。 * http://m.survivalescaperooms.com/deepleo/*--------------------------------------------------------------------------*/using System;using System.Collections;using System.Collections.Generic;using System.Diagnostics;using System.Dynamic;using System.IO;using System.Linq;using System.Reflection;using System.Runtime.Serialization.Json;using System.Text;using System.Xml;using System.Xml.Linq;namespace Codeplex.Data{ public class DynamicJson : DynamicObject { private enum JsonType { @string, number, boolean, @object, array, @null } // public static methods /// <summary>from JsonSring to DynamicJson</summary> public static dynamic Parse(string json) { return Parse(json, Encoding.Unicode); } /// <summary>from JsonSring to DynamicJson</summary> public static dynamic Parse(string json, Encoding encoding) { using (var reader = JsonReaderWriterFactory.CreateJsonReader(encoding.GetBytes(json), XmlDictionaryReaderQuotas.Max)) { return ToValue(XElement.Load(reader)); } } /// <summary>from JsonSringStream to DynamicJson</summary> public static dynamic Parse(Stream stream) { using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max)) { return ToValue(XElement.Load(reader)); } } /// <summary>from JsonSringStream to DynamicJson</summary> public static dynamic Parse(Stream stream, Encoding encoding) { using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, encoding, XmlDictionaryReaderQuotas.Max, _ => { })) { return ToValue(XElement.Load(reader)); } } /// <summary>create JsonSring from primitive or IEnumerable or Object({public property name:property value})</summary> public static string Serialize(object obj) { return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(GetJsonType(obj)), CreateJsonNode(obj))); } // private static methods private static dynamic ToValue(XElement element) { var type = (JsonType)Enum.Parse(typeof(JsonType), element.Attribute("type").Value); switch (type) { case JsonType.boolean: return (bool)element; case JsonType.number: return (double)element; case JsonType.@string: return (string)element; case JsonType.@object: case JsonType.array: return new DynamicJson(element, type); case JsonType.@null: default: return null; } } private static JsonType GetJsonType(object obj) { if (obj == null) return JsonType.@null; switch (Type.GetTypeCode(obj.GetType())) { case TypeCode.Boolean: return JsonType.boolean; case TypeCode.String: case TypeCode.Char: case TypeCode.DateTime: return JsonType.@string; case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCode.SByte: case TypeCode.Byt
新聞熱點
疑難解答