ReflectionInfo.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. var loading = into as IJsonLoading;
  95. if (loading != null)
  96. loading.OnJsonLoading(r);
  97. r.ParseDictionary(key =>
  98. {
  99. ParseFieldOrProperty(r, into, key);
  100. });
  101. var loaded = into as IJsonLoaded;
  102. if (loaded != null)
  103. loaded.OnJsonLoaded(r);
  104. }
  105. // The member info is stored in a list (as opposed to a dictionary) so that
  106. // the json is written in the same order as the fields/properties are defined
  107. // On loading, we assume the fields will be in the same order, but need to
  108. // handle if they're not. This function performs a linear search, but
  109. // starts after the last found item as an optimization that should work
  110. // most of the time.
  111. int _lastFoundIndex = 0;
  112. bool FindMemberInfo(string name, out JsonMemberInfo found)
  113. {
  114. for (int i = 0; i < Members.Count; i++)
  115. {
  116. int index = (i + _lastFoundIndex) % Members.Count;
  117. var jmi = Members[index];
  118. if (jmi.JsonKey == name)
  119. {
  120. _lastFoundIndex = index;
  121. found = jmi;
  122. return true;
  123. }
  124. }
  125. found = null;
  126. return false;
  127. }
  128. // Parse a value from IJsonReader into an object instance
  129. public void ParseFieldOrProperty(IJsonReader r, object into, string key)
  130. {
  131. // IJsonLoadField
  132. var lf = into as IJsonLoadField;
  133. if (lf != null && lf.OnJsonField(r, key))
  134. return;
  135. // Find member
  136. JsonMemberInfo jmi;
  137. if (FindMemberInfo(key, out jmi))
  138. {
  139. // Try to keep existing instance
  140. if (jmi.KeepInstance)
  141. {
  142. var subInto = jmi.GetValue(into);
  143. if (subInto != null)
  144. {
  145. r.ParseInto(subInto);
  146. return;
  147. }
  148. }
  149. // Parse and set
  150. var val = r.Parse(jmi.MemberType);
  151. jmi.SetValue(into, val);
  152. return;
  153. }
  154. }
  155. // Get the reflection info for a specified type
  156. public static ReflectionInfo GetReflectionInfo(Type type)
  157. {
  158. // Check cache
  159. return _cache.Get(type, () =>
  160. {
  161. var allMembers = Utils.GetAllFieldsAndProperties(type);
  162. // Does type have a [Json] attribute
  163. var typeAttr = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().FirstOrDefault();
  164. bool typeMarked = typeAttr != null;
  165. // Do any members have a [Json] attribute
  166. bool anyFieldsMarked = allMembers.Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
  167. // If the type is marked with [Json(ExplicitFieldsOnly = true)] then ignore the type attribute
  168. // and only serialize fields explicitly marked.
  169. if (typeAttr != null && typeAttr.ExplicitMembersOnly)
  170. {
  171. anyFieldsMarked = true;
  172. typeAttr = null;
  173. typeMarked = false;
  174. }
  175. // Try with DataContract and friends
  176. if (!typeMarked && !anyFieldsMarked && type.GetCustomAttributes(typeof(DataContractAttribute), true).OfType<DataContractAttribute>().Any())
  177. {
  178. var ri = CreateReflectionInfo(type, mi =>
  179. {
  180. // Get attributes
  181. var attr = mi.GetCustomAttributes(typeof(DataMemberAttribute), false).OfType<DataMemberAttribute>().FirstOrDefault();
  182. if (attr != null)
  183. {
  184. return new JsonMemberInfo()
  185. {
  186. Member = mi,
  187. JsonKey = attr.Name ?? mi.Name, // No lower case first letter if using DataContract/Member
  188. };
  189. }
  190. return null;
  191. });
  192. ri.Members.Sort((a, b) => String.CompareOrdinal(a.JsonKey, b.JsonKey)); // Match DataContractJsonSerializer
  193. return ri;
  194. }
  195. {
  196. // Should we serialize all public methods?
  197. bool serializeAllPublics = typeMarked || !anyFieldsMarked;
  198. // Build
  199. var ri = CreateReflectionInfo(type, mi =>
  200. {
  201. // Explicitly excluded?
  202. if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).Any())
  203. return null;
  204. // Get attributes
  205. var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
  206. if (attr != null)
  207. {
  208. return new JsonMemberInfo()
  209. {
  210. Member = mi,
  211. JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  212. Attribute = attr,
  213. };
  214. }
  215. // Serialize all publics?
  216. if (serializeAllPublics && Utils.IsPublic(mi))
  217. {
  218. return new JsonMemberInfo()
  219. {
  220. Member = mi,
  221. JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  222. };
  223. }
  224. return null;
  225. });
  226. return ri;
  227. }
  228. });
  229. }
  230. public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
  231. {
  232. // Work out properties and fields
  233. var members = Utils.GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
  234. // Anything with KeepInstance must be a reference type
  235. var invalid = members.FirstOrDefault(x => x.KeepInstance && x.MemberType.IsValueType);
  236. if (invalid!=null)
  237. {
  238. throw new InvalidOperationException(string.Format("KeepInstance=true can only be applied to reference types ({0}.{1})", type.FullName, invalid.Member));
  239. }
  240. // Must have some members
  241. /*
  242. if (!members.Any() && !Attribute.IsDefined(type, typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false))
  243. return null;
  244. */
  245. // Create reflection info
  246. return new ReflectionInfo() { Members = members };
  247. }
  248. }
  249. }