ReflectionInfo.cs 10 KB

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