JsonUtilityExtension.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using UnityEngine;
  5. namespace UniWebViewExternal {
  6. // A JSON utility extension which supports top-level simple types, arrays, and generic lists.
  7. public static class UniWebViewJsonUtility {
  8. public static T FromJson<T>(string json) {
  9. if (json == null) {
  10. return default(T);
  11. }
  12. json = json.Trim();
  13. Type type = typeof(T);
  14. if (IsSimpleType(type)) {
  15. return ParseSimpleType<T>(json);
  16. }
  17. if (type.IsArray) {
  18. return ParseArray<T>(json);
  19. }
  20. if (IsGenericList(type)) {
  21. return ParseList<T>(json);
  22. }
  23. try {
  24. return JsonUtility.FromJson<T>(json);
  25. } catch {
  26. // 如果失败,尝试包装后解析
  27. return ParseWrappedValue<T>(json);
  28. }
  29. }
  30. public static string ToJson(object obj, bool prettyPrint = false) {
  31. if (obj == null) {
  32. return "null";
  33. }
  34. Type type = obj.GetType();
  35. if (IsSimpleType(type)) {
  36. return ConvertSimpleTypeToJson(obj);
  37. }
  38. if (type.IsArray) {
  39. return ConvertArrayToJson(obj, prettyPrint);
  40. }
  41. if (IsGenericList(type)) {
  42. return ConvertListToJson(obj, prettyPrint);
  43. }
  44. // Use optimized approach: try Unity first, fallback to reflection if needed
  45. return ToJsonOptimized(obj, prettyPrint);
  46. }
  47. private static bool IsSimpleType(Type type) {
  48. return type == typeof(string) ||
  49. type == typeof(int) ||
  50. type == typeof(float) ||
  51. type == typeof(double) ||
  52. type == typeof(bool) ||
  53. type == typeof(long) ||
  54. type == typeof(short) ||
  55. type == typeof(byte) ||
  56. type == typeof(char);
  57. }
  58. private static bool IsGenericList(Type type) {
  59. return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>);
  60. }
  61. // Cache for type serialization capability to avoid repeated reflection
  62. private static readonly System.Collections.Generic.Dictionary<System.Type, bool> _typeSerializabilityCache
  63. = new System.Collections.Generic.Dictionary<System.Type, bool>();
  64. private static string ToJsonOptimized(object obj, bool prettyPrint) {
  65. Type type = obj.GetType();
  66. // Check cache first
  67. bool canUseUnityJson;
  68. if (_typeSerializabilityCache.TryGetValue(type, out canUseUnityJson)) {
  69. if (canUseUnityJson) {
  70. return JsonUtility.ToJson(obj, prettyPrint);
  71. } else {
  72. return ConvertObjectWithReflection(obj);
  73. }
  74. }
  75. // Not in cache, determine serializability using fast checks first
  76. bool fastCheck = CanUseUnityJsonUtilityFast(type);
  77. if (fastCheck) {
  78. // Fast check says it should work, use Unity JsonUtility
  79. _typeSerializabilityCache[type] = true;
  80. return JsonUtility.ToJson(obj, prettyPrint);
  81. }
  82. // Fast check failed, try Unity JsonUtility and verify result
  83. string unityResult = JsonUtility.ToJson(obj, prettyPrint);
  84. if (unityResult != "{}" || !HasSerializableContent(obj)) {
  85. // Unity succeeded or object is actually empty
  86. _typeSerializabilityCache[type] = true;
  87. return unityResult;
  88. }
  89. // Unity failed, use reflection and cache the result
  90. _typeSerializabilityCache[type] = false;
  91. return ConvertObjectWithReflection(obj);
  92. }
  93. private static bool CanUseUnityJsonUtilityFast(System.Type type) {
  94. // Fast checks without serialization test
  95. // Check if type has [Serializable] attribute
  96. if (System.Attribute.IsDefined(type, typeof(System.SerializableAttribute))) {
  97. return true;
  98. }
  99. // Check if it's a MonoBehaviour or ScriptableObject
  100. if (typeof(MonoBehaviour).IsAssignableFrom(type) ||
  101. typeof(ScriptableObject).IsAssignableFrom(type)) {
  102. return true;
  103. }
  104. // Check if it's a struct (structs are serializable by default in Unity)
  105. if (type.IsValueType && !type.IsEnum && !type.IsPrimitive) {
  106. return true;
  107. }
  108. // Anonymous types and non-serializable classes will fail fast check
  109. return false;
  110. }
  111. private static bool HasSerializableContent(object obj) {
  112. if (obj == null) return false;
  113. Type type = obj.GetType();
  114. // Check if object has any public fields or properties
  115. var properties = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
  116. var fields = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
  117. foreach (var prop in properties) {
  118. if (prop.CanRead && prop.GetIndexParameters().Length == 0) {
  119. try {
  120. var value = prop.GetValue(obj);
  121. if (value != null) return true;
  122. } catch {
  123. // Skip properties that can't be read
  124. }
  125. }
  126. }
  127. foreach (var field in fields) {
  128. try {
  129. var value = field.GetValue(obj);
  130. if (value != null) return true;
  131. } catch {
  132. // Skip fields that can't be read
  133. }
  134. }
  135. return false;
  136. }
  137. private static T ParseSimpleType<T>(string json) {
  138. Type type = typeof(T);
  139. json = json.Trim();
  140. try {
  141. if (type == typeof(string)) {
  142. // 移除引号
  143. if (json.StartsWith("\"") && json.EndsWith("\"")) {
  144. json = json.Substring(1, json.Length - 2);
  145. json = UnescapeJsonString(json);
  146. }
  147. return (T)(object)json;
  148. } else if (type == typeof(int)) {
  149. return (T)(object)int.Parse(json, CultureInfo.InvariantCulture);
  150. } else if (type == typeof(float)) {
  151. return (T)(object)float.Parse(json, CultureInfo.InvariantCulture);
  152. } else if (type == typeof(double)) {
  153. return (T)(object)double.Parse(json, CultureInfo.InvariantCulture);
  154. } else if (type == typeof(bool)) {
  155. return (T)(object)bool.Parse(json);
  156. } else if (type == typeof(long)) {
  157. return (T)(object)long.Parse(json, CultureInfo.InvariantCulture);
  158. } else if (type == typeof(short)) {
  159. return (T)(object)short.Parse(json, CultureInfo.InvariantCulture);
  160. } else if (type == typeof(byte)) {
  161. return (T)(object)byte.Parse(json, CultureInfo.InvariantCulture);
  162. } else if (type == typeof(char)) {
  163. if (json.StartsWith("\"") && json.EndsWith("\"") && json.Length == 3) {
  164. return (T)(object)json[1];
  165. }
  166. return (T)(object)char.Parse(json);
  167. }
  168. } catch (Exception e) {
  169. UniWebViewLogger.Instance.Critical($"Failed to parse simple type {type.Name}: {e.Message}");
  170. }
  171. return default(T);
  172. }
  173. private static T ParseArray<T>(string json) {
  174. Type elementType = typeof(T).GetElementType();
  175. string wrappedJson = $"{{\"items\":{json}}}";
  176. Type wrapperType = typeof(ArrayWrapper<>).MakeGenericType(elementType);
  177. object wrapper = JsonUtility.FromJson(wrappedJson, wrapperType);
  178. var itemsField = wrapperType.GetField("items");
  179. return (T)itemsField.GetValue(wrapper);
  180. }
  181. private static T ParseList<T>(string json) {
  182. Type elementType = typeof(T).GetGenericArguments()[0];
  183. string wrappedJson = $"{{\"items\":{json}}}";
  184. Type wrapperType = typeof(ArrayWrapper<>).MakeGenericType(elementType);
  185. object wrapper = JsonUtility.FromJson(wrappedJson, wrapperType);
  186. var itemsField = wrapperType.GetField("items");
  187. Array array = (Array)itemsField.GetValue(wrapper);
  188. Type listType = typeof(List<>).MakeGenericType(elementType);
  189. var list = Activator.CreateInstance(listType);
  190. var addMethod = listType.GetMethod("Add");
  191. foreach (var item in array) {
  192. addMethod.Invoke(list, new[] { item });
  193. }
  194. return (T)list;
  195. }
  196. private static T ParseWrappedValue<T>(string json) {
  197. string wrappedJson = $"{{\"value\":{json}}}";
  198. try {
  199. var wrapper = JsonUtility.FromJson<ValueWrapper<T>>(wrappedJson);
  200. return wrapper.value;
  201. } catch {
  202. UniWebViewLogger.Instance.Critical($"Failed to parse JSON: {json}");
  203. return default(T);
  204. }
  205. }
  206. // Single-pass unescape for the small set of escapes produced by ConvertSimpleTypeToJson
  207. // (\" \\ \n \r \t). A chained String.Replace is wrong here: unescaping "\\" to "\" first can
  208. // turn a literal "\\n" (backslash + n) into a newline on a later pass.
  209. private static string UnescapeJsonString(string s) {
  210. var sb = new System.Text.StringBuilder(s.Length);
  211. for (int i = 0; i < s.Length; i++) {
  212. char c = s[i];
  213. if (c == '\\' && i + 1 < s.Length) {
  214. char next = s[i + 1];
  215. switch (next) {
  216. case '"': sb.Append('"'); i++; break;
  217. case '\\': sb.Append('\\'); i++; break;
  218. case 'n': sb.Append('\n'); i++; break;
  219. case 'r': sb.Append('\r'); i++; break;
  220. case 't': sb.Append('\t'); i++; break;
  221. default: sb.Append(c); break;
  222. }
  223. } else {
  224. sb.Append(c);
  225. }
  226. }
  227. return sb.ToString();
  228. }
  229. private static string ConvertSimpleTypeToJson(object obj) {
  230. Type type = obj.GetType();
  231. if (type == typeof(string)) {
  232. string str = (string)obj;
  233. str = str.Replace("\\", "\\\\")
  234. .Replace("\"", "\\\"")
  235. .Replace("\n", "\\n")
  236. .Replace("\r", "\\r")
  237. .Replace("\t", "\\t");
  238. return $"\"{str}\"";
  239. } else if (type == typeof(bool)) {
  240. return obj.ToString().ToLower();
  241. } else if (type == typeof(float) || type == typeof(double)) {
  242. // Format with the invariant culture so the JSON always uses '.' as the decimal
  243. // separator, regardless of the app's current culture. The old Replace(",", ".")
  244. // hack produced invalid JSON under cultures that use '.' as a thousands separator.
  245. return ((IFormattable)obj).ToString(null, CultureInfo.InvariantCulture);
  246. } else if (type == typeof(char)) {
  247. return $"\"{obj}\"";
  248. } else {
  249. return obj.ToString();
  250. }
  251. }
  252. private static string ConvertArrayToJson(object obj, bool prettyPrint) {
  253. Array array = (Array)obj;
  254. Type elementType = obj.GetType().GetElementType();
  255. // Handle object arrays or mixed-type arrays using reflection
  256. if (elementType == typeof(object) || !CanUseUnityJsonUtilityFast(elementType)) {
  257. var sb = new System.Text.StringBuilder("[");
  258. for (int i = 0; i < array.Length; i++) {
  259. if (i > 0) sb.Append(",");
  260. sb.Append(ConvertObjectWithReflection(array.GetValue(i)));
  261. }
  262. sb.Append("]");
  263. return sb.ToString();
  264. }
  265. // Use Unity's JsonUtility for homogeneous typed arrays
  266. Type wrapperType = typeof(ArrayWrapper<>).MakeGenericType(elementType);
  267. object wrapper = Activator.CreateInstance(wrapperType);
  268. var itemsField = wrapperType.GetField("items");
  269. itemsField.SetValue(wrapper, array);
  270. string json = JsonUtility.ToJson(wrapper, prettyPrint);
  271. int start = json.IndexOf("[");
  272. int end = json.LastIndexOf("]") + 1;
  273. return json.Substring(start, end - start);
  274. }
  275. private static string ConvertListToJson(object obj, bool prettyPrint) {
  276. Type elementType = obj.GetType().GetGenericArguments()[0];
  277. // 转换 List 为数组
  278. var toArrayMethod = obj.GetType().GetMethod("ToArray");
  279. Array array = (Array)toArrayMethod.Invoke(obj, null);
  280. return ConvertArrayToJson(array, prettyPrint);
  281. }
  282. private static string ConvertObjectWithReflection(object obj) {
  283. if (obj == null) return "null";
  284. Type type = obj.GetType();
  285. // Handle basic types that might not be caught by IsSimpleType
  286. if (type.IsPrimitive || type == typeof(string) || type == typeof(decimal)) {
  287. return ConvertSimpleTypeToJson(obj);
  288. }
  289. // Handle collections
  290. if (obj is System.Collections.IEnumerable enumerable && !(obj is string)) {
  291. var sb = new System.Text.StringBuilder("[");
  292. bool flag = true;
  293. foreach (var item in enumerable) {
  294. if (!flag) sb.Append(",");
  295. sb.Append(ConvertObjectWithReflection(item));
  296. flag = false;
  297. }
  298. sb.Append("]");
  299. return sb.ToString();
  300. }
  301. // Handle objects using reflection
  302. var json = new System.Text.StringBuilder("{");
  303. var properties = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
  304. var fields = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
  305. bool first = true;
  306. // Serialize properties
  307. foreach (var prop in properties) {
  308. if (prop.CanRead && prop.GetIndexParameters().Length == 0) { // Skip indexers
  309. try {
  310. var value = prop.GetValue(obj);
  311. if (!first) json.Append(",");
  312. json.Append("\"").Append(prop.Name).Append("\":");
  313. json.Append(ConvertObjectWithReflection(value));
  314. first = false;
  315. } catch {
  316. // Skip properties that can't be read
  317. }
  318. }
  319. }
  320. // Serialize fields
  321. foreach (var field in fields) {
  322. try {
  323. var value = field.GetValue(obj);
  324. if (!first) json.Append(",");
  325. json.Append("\"").Append(field.Name).Append("\":");
  326. json.Append(ConvertObjectWithReflection(value));
  327. first = false;
  328. } catch {
  329. // Skip fields that can't be read
  330. }
  331. }
  332. json.Append("}");
  333. return json.ToString();
  334. }
  335. [Serializable]
  336. private class ArrayWrapper<T> {
  337. public T[] items;
  338. }
  339. [Serializable]
  340. private class ValueWrapper<T> {
  341. public T value;
  342. }
  343. }
  344. }