ReflectionInfo.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. // Define JsonKit_NO_DYNAMIC to disable Expando support
  15. // Define JsonKit_NO_EMIT to disable Reflection.Emit
  16. // Define JsonKit_NO_DATACONTRACT to disable support for [DataContract]/[DataMember]
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Linq;
  20. using System.Reflection;
  21. using System.Runtime.Serialization;
  22. namespace Topten.JsonKit
  23. {
  24. // Stores reflection info about a type
  25. class ReflectionInfo
  26. {
  27. // List of members to be serialized
  28. public List<JsonMemberInfo> Members;
  29. // Cache of these ReflectionInfos's
  30. static ThreadSafeCache<Type, ReflectionInfo> _cache = new ThreadSafeCache<Type, ReflectionInfo>();
  31. public static MethodInfo FindFormatJson(Type type)
  32. {
  33. if (type.IsValueType)
  34. {
  35. // Try `void FormatJson(IJsonWriter)`
  36. var formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IJsonWriter) }, null);
  37. if (formatJson != null && formatJson.ReturnType == typeof(void))
  38. return formatJson;
  39. // Try `string FormatJson()`
  40. formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);
  41. if (formatJson != null && formatJson.ReturnType == typeof(string))
  42. return formatJson;
  43. }
  44. return null;
  45. }
  46. public static MethodInfo FindParseJson(Type type)
  47. {
  48. // Try `T ParseJson(IJsonReader)`
  49. var parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(IJsonReader) }, null);
  50. if (parseJson != null && parseJson.ReturnType == type)
  51. return parseJson;
  52. // Try `T ParseJson(string)`
  53. parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
  54. if (parseJson != null && parseJson.ReturnType == type)
  55. return parseJson;
  56. return null;
  57. }
  58. // Write one of these types
  59. public void Write(IJsonWriter w, object val)
  60. {
  61. w.WriteDictionary(() =>
  62. {
  63. var writing = val as IJsonWriting;
  64. if (writing != null)
  65. writing.OnJsonWriting(w);
  66. foreach (var jmi in Members.Where(x=>!x.Deprecated))
  67. {
  68. w.WriteKeyNoEscaping(jmi.JsonKey);
  69. w.WriteValue(jmi.GetValue(val));
  70. }
  71. var written = val as IJsonWritten;
  72. if (written != null)
  73. written.OnJsonWritten(w);
  74. });
  75. }
  76. // Read one of these types.
  77. // NB: Although JsonKit.JsonParseInto only works on reference type, when using reflection
  78. // it also works for value types so we use the one method for both
  79. public void ParseInto(IJsonReader r, object into)
  80. {
  81. var loading = into as IJsonLoading;
  82. if (loading != null)
  83. loading.OnJsonLoading(r);
  84. r.ParseDictionary(key =>
  85. {
  86. ParseFieldOrProperty(r, into, key);
  87. });
  88. var loaded = into as IJsonLoaded;
  89. if (loaded != null)
  90. loaded.OnJsonLoaded(r);
  91. }
  92. // The member info is stored in a list (as opposed to a dictionary) so that
  93. // the json is written in the same order as the fields/properties are defined
  94. // On loading, we assume the fields will be in the same order, but need to
  95. // handle if they're not. This function performs a linear search, but
  96. // starts after the last found item as an optimization that should work
  97. // most of the time.
  98. int _lastFoundIndex = 0;
  99. bool FindMemberInfo(string name, out JsonMemberInfo found)
  100. {
  101. for (int i = 0; i < Members.Count; i++)
  102. {
  103. int index = (i + _lastFoundIndex) % Members.Count;
  104. var jmi = Members[index];
  105. if (jmi.JsonKey == name)
  106. {
  107. _lastFoundIndex = index;
  108. found = jmi;
  109. return true;
  110. }
  111. }
  112. found = null;
  113. return false;
  114. }
  115. // Parse a value from IJsonReader into an object instance
  116. public void ParseFieldOrProperty(IJsonReader r, object into, string key)
  117. {
  118. // IJsonLoadField
  119. var lf = into as IJsonLoadField;
  120. if (lf != null && lf.OnJsonField(r, key))
  121. return;
  122. // Find member
  123. JsonMemberInfo jmi;
  124. if (FindMemberInfo(key, out jmi))
  125. {
  126. // Try to keep existing instance
  127. if (jmi.KeepInstance)
  128. {
  129. var subInto = jmi.GetValue(into);
  130. if (subInto != null)
  131. {
  132. r.ParseInto(subInto);
  133. return;
  134. }
  135. }
  136. // Parse and set
  137. var val = r.Parse(jmi.MemberType);
  138. jmi.SetValue(into, val);
  139. return;
  140. }
  141. }
  142. // Get the reflection info for a specified type
  143. public static ReflectionInfo GetReflectionInfo(Type type)
  144. {
  145. // Check cache
  146. return _cache.Get(type, () =>
  147. {
  148. var allMembers = Utils.GetAllFieldsAndProperties(type);
  149. // Does type have a [Json] attribute
  150. bool typeMarked = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().Any();
  151. // Do any members have a [Json] attribute
  152. bool anyFieldsMarked = allMembers.Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
  153. // Try with DataContract and friends
  154. if (!typeMarked && !anyFieldsMarked && type.GetCustomAttributes(typeof(DataContractAttribute), true).OfType<DataContractAttribute>().Any())
  155. {
  156. var ri = CreateReflectionInfo(type, mi =>
  157. {
  158. // Get attributes
  159. var attr = mi.GetCustomAttributes(typeof(DataMemberAttribute), false).OfType<DataMemberAttribute>().FirstOrDefault();
  160. if (attr != null)
  161. {
  162. return new JsonMemberInfo()
  163. {
  164. Member = mi,
  165. JsonKey = attr.Name ?? mi.Name, // No lower case first letter if using DataContract/Member
  166. };
  167. }
  168. return null;
  169. });
  170. ri.Members.Sort((a, b) => String.CompareOrdinal(a.JsonKey, b.JsonKey)); // Match DataContractJsonSerializer
  171. return ri;
  172. }
  173. {
  174. // Should we serialize all public methods?
  175. bool serializeAllPublics = typeMarked || !anyFieldsMarked;
  176. // Build
  177. var ri = CreateReflectionInfo(type, mi =>
  178. {
  179. // Explicitly excluded?
  180. if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).Any())
  181. return null;
  182. // Get attributes
  183. var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
  184. if (attr != null)
  185. {
  186. return new JsonMemberInfo()
  187. {
  188. Member = mi,
  189. JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  190. KeepInstance = attr.KeepInstance,
  191. Deprecated = attr.Deprecated,
  192. };
  193. }
  194. // Serialize all publics?
  195. if (serializeAllPublics && Utils.IsPublic(mi))
  196. {
  197. return new JsonMemberInfo()
  198. {
  199. Member = mi,
  200. JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  201. };
  202. }
  203. return null;
  204. });
  205. return ri;
  206. }
  207. });
  208. }
  209. public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
  210. {
  211. // Work out properties and fields
  212. var members = Utils.GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
  213. // Anything with KeepInstance must be a reference type
  214. var invalid = members.FirstOrDefault(x => x.KeepInstance && x.MemberType.IsValueType);
  215. if (invalid!=null)
  216. {
  217. throw new InvalidOperationException(string.Format("KeepInstance=true can only be applied to reference types ({0}.{1})", type.FullName, invalid.Member));
  218. }
  219. // Must have some members
  220. if (!members.Any() && !Attribute.IsDefined(type, typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), false))
  221. return null;
  222. // Create reflection info
  223. return new ReflectionInfo() { Members = members };
  224. }
  225. }
  226. }