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