ReflectionInfo.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // JsonKit v0.5 - A simple but flexible Json library in a single .cs file.
  2. //
  3. // Copyright (C) 2014 Topten Software (contact@toptensoftware.com) All rights reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
  6. // except in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the
  11. // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. // either express or implied. See the License for the specific language governing permissions
  13. // and limitations under the License.
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.Reflection;
  18. using System.Runtime.Serialization;
  19. namespace Topten.JsonKit
  20. {
  21. // Stores reflection info about a type
  22. class ReflectionInfo
  23. {
  24. // List of members to be serialized
  25. public List<JsonMemberInfo> Members;
  26. // Cache of these ReflectionInfos's
  27. static ThreadSafeCache<Type, ReflectionInfo> _cache = new ThreadSafeCache<Type, ReflectionInfo>();
  28. public static MethodInfo FindFormatJson(Type type)
  29. {
  30. if (type.IsValueType)
  31. {
  32. // Try `void FormatJson(IJsonWriter)`
  33. var formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IJsonWriter) }, null);
  34. if (formatJson != null && formatJson.ReturnType == typeof(void))
  35. return formatJson;
  36. // Try `string FormatJson()`
  37. formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);
  38. if (formatJson != null && formatJson.ReturnType == typeof(string))
  39. return formatJson;
  40. }
  41. return null;
  42. }
  43. public static MethodInfo FindParseJson(Type type)
  44. {
  45. // Try `T ParseJson(IJsonReader)`
  46. var parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(IJsonReader) }, null);
  47. if (parseJson != null && parseJson.ReturnType == type)
  48. return parseJson;
  49. // Try `T ParseJson(string)`
  50. parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
  51. if (parseJson != null && parseJson.ReturnType == type)
  52. return parseJson;
  53. return null;
  54. }
  55. // Write one of these types
  56. public void Write(IJsonWriter w, object val)
  57. {
  58. w.WriteDictionary(() =>
  59. {
  60. var writing = val as IJsonWriting;
  61. if (writing != null)
  62. writing.OnJsonWriting(w);
  63. foreach (var jmi in Members.Where(x=>!x.Deprecated))
  64. {
  65. // Exclude null?
  66. var mval = jmi.GetValue(val);
  67. if (jmi.ExcludeIfNull && mval == null)
  68. continue;
  69. if (jmi.ExcludeIfEmpty)
  70. {
  71. if (mval == null)
  72. continue;
  73. if (mval is System.Collections.IEnumerable e && !e.GetEnumerator().MoveNext())
  74. continue;
  75. }
  76. if (jmi.ExcludeIfEquals != null)
  77. {
  78. if (jmi.ExcludeIfEquals.Equals(mval))
  79. continue;
  80. }
  81. w.WriteKeyNoEscaping(jmi.JsonKey);
  82. w.WriteValue(mval);
  83. }
  84. var written = val as IJsonWritten;
  85. if (written != null)
  86. written.OnJsonWritten(w);
  87. });
  88. }
  89. // Read one of these types.
  90. // NB: Although JsonKit.JsonParseInto only works on reference type, when using reflection
  91. // it also works for value types so we use the one method for both
  92. public void ParseInto(IJsonReader r, object into)
  93. {
  94. try
  95. {
  96. var loading = into as IJsonLoading;
  97. if (loading != null)
  98. loading.OnJsonLoading(r);
  99. r.ParseDictionary(key =>
  100. {
  101. ParseFieldOrProperty(r, into, key);
  102. });
  103. var loaded = into as IJsonLoaded;
  104. if (loaded != null)
  105. loaded.OnJsonLoaded(r);
  106. }
  107. catch (Exception x)
  108. {
  109. var loadex = into as IJsonLoadException;
  110. if (loadex != null)
  111. loadex.OnJsonLoadException(r, x);
  112. }
  113. }
  114. // The member info is stored in a list (as opposed to a dictionary) so that
  115. // the json is written in the same order as the fields/properties are defined
  116. // On loading, we assume the fields will be in the same order, but need to
  117. // handle if they're not. This function performs a linear search, but
  118. // starts after the last found item as an optimization that should work
  119. // most of the time.
  120. int _lastFoundIndex = 0;
  121. bool FindMemberInfo(string name, out JsonMemberInfo found)
  122. {
  123. for (int i = 0; i < Members.Count; i++)
  124. {
  125. int index = (i + _lastFoundIndex) % Members.Count;
  126. var jmi = Members[index];
  127. if (jmi.JsonKey == name)
  128. {
  129. _lastFoundIndex = index;
  130. found = jmi;
  131. return true;
  132. }
  133. }
  134. found = null;
  135. return false;
  136. }
  137. // Parse a value from IJsonReader into an object instance
  138. public void ParseFieldOrProperty(IJsonReader r, object into, string key)
  139. {
  140. // IJsonLoadField
  141. var lf = into as IJsonLoadField;
  142. if (lf != null && lf.OnJsonField(r, key))
  143. return;
  144. // Find member
  145. JsonMemberInfo jmi;
  146. if (FindMemberInfo(key, out jmi))
  147. {
  148. // Try to keep existing instance
  149. if (jmi.KeepInstance)
  150. {
  151. var subInto = jmi.GetValue(into);
  152. if (subInto != null)
  153. {
  154. r.ParseInto(subInto);
  155. return;
  156. }
  157. }
  158. // Parse and set
  159. var val = r.Parse(jmi.MemberType);
  160. jmi.SetValue(into, val);
  161. return;
  162. }
  163. }
  164. // Get the reflection info for a specified type
  165. public static ReflectionInfo GetReflectionInfo(Type type)
  166. {
  167. // Check cache
  168. return _cache.Get(type, () =>
  169. {
  170. var allMembers = Utils.GetAllFieldsAndProperties(type);
  171. // Does type have a [Json] attribute
  172. var typeAttr = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().FirstOrDefault();
  173. bool typeMarked = typeAttr != null;
  174. // Do any members have a [Json] attribute
  175. bool anyFieldsMarked = allMembers.Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
  176. // If the type is marked with [Json(ExplicitFieldsOnly = true)] then ignore the type attribute
  177. // and only serialize fields explicitly marked.
  178. if (typeAttr != null && typeAttr.ExplicitMembersOnly)
  179. {
  180. anyFieldsMarked = true;
  181. typeAttr = null;
  182. typeMarked = false;
  183. }
  184. // Try with DataContract and friends
  185. if (!typeMarked && !anyFieldsMarked && type.GetCustomAttributes(typeof(DataContractAttribute), true).OfType<DataContractAttribute>().Any())
  186. {
  187. var ri = CreateReflectionInfo(type, mi =>
  188. {
  189. // Get attributes
  190. var attr = mi.GetCustomAttributes(typeof(DataMemberAttribute), false).OfType<DataMemberAttribute>().FirstOrDefault();
  191. if (attr != null)
  192. {
  193. return new JsonMemberInfo()
  194. {
  195. Member = mi,
  196. JsonKey = attr.Name ?? mi.Name, // No lower case first letter if using DataContract/Member
  197. };
  198. }
  199. return null;
  200. });
  201. ri.Members.Sort((a, b) => String.CompareOrdinal(a.JsonKey, b.JsonKey)); // Match DataContractJsonSerializer
  202. return ri;
  203. }
  204. {
  205. // Should we serialize all public methods?
  206. bool serializeAllPublics = typeMarked || !anyFieldsMarked;
  207. // Build
  208. var ri = CreateReflectionInfo(type, mi =>
  209. {
  210. // Explicitly excluded?
  211. if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).Any())
  212. return null;
  213. // Get attributes
  214. var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
  215. if (attr != null)
  216. {
  217. return new JsonMemberInfo()
  218. {
  219. Member = mi,
  220. JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  221. Attribute = attr,
  222. };
  223. }
  224. // Serialize all publics?
  225. if (serializeAllPublics && Utils.IsPublic(mi))
  226. {
  227. return new JsonMemberInfo()
  228. {
  229. Member = mi,
  230. JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  231. };
  232. }
  233. return null;
  234. });
  235. return ri;
  236. }
  237. });
  238. }
  239. public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
  240. {
  241. // Work out properties and fields
  242. var members = Utils.GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
  243. // Anything with KeepInstance must be a reference type
  244. var invalid = members.FirstOrDefault(x => x.KeepInstance && x.MemberType.IsValueType);
  245. if (invalid!=null)
  246. {
  247. throw new InvalidOperationException(string.Format("KeepInstance=true can only be applied to reference types ({0}.{1})", type.FullName, invalid.Member));
  248. }
  249. // Must have some members
  250. /*
  251. if (!members.Any() && !Attribute.IsDefined(type, typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false))
  252. return null;
  253. */
  254. // Create reflection info
  255. return new ReflectionInfo() { Members = members };
  256. }
  257. }
  258. }