-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleJson.cs
More file actions
4437 lines (3994 loc) · 173 KB
/
Copy pathSimpleJson.cs
File metadata and controls
4437 lines (3994 loc) · 173 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////-----------------------------------------------------------------------
//// <copyright file="SimpleJson.cs" company="The Outercurve Foundation">
//// Copyright (c) 2011, The Outercurve Foundation.
////
//// Licensed under the MIT License (the "License");
//// you may not use this file except in compliance with the License.
//// You may obtain a copy of the License at
//// http://www.opensource.org/licenses/mit-license.php
////
//// Unless required by applicable law or agreed to in writing, software
//// distributed under the License is distributed on an "AS IS" BASIS,
//// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//// See the License for the specific language governing permissions and
//// limitations under the License.
//// </copyright>
//// <website>https://github.com/facebook-csharp-sdk/simple-json</website>
/// RS.SimpleJson-Unity is a fork of the original SimpleJson library, with modifications to support Unity and additional features.
/// <Author>andyhebear</Author>
/// <website>https://github.com/RS-Unity3D/RS.SimpleJson-Unity</website>
////-----------------------------------------------------------------------
////sgd:2026.4.30 Add Circular Reference Detection support
////sgd:2026.4.13 Improve code quality
////sgd:2026.4.2 be compatible with simplejson v2.0.0 as much as possible
////sgd:2026.3.20 refactoring
////sgd:2026.2.20 support aot compiler
////sgd: 2025.12.15 support unity 3d
////sgd: 2025.11.10 support property To lower case
////sgd: 2025.10.1 support string key dictionary
//// VERSION: 2.2.0.0
////NOTE:need AOT support,need #define SIMPLE_JSON_AOT
//#define SIMPLE_JSON_AOT
////NOTE: uncomment the following line to make SimpleJson class internal.
////#define SIMPLE_JSON_INTERNAL
//// NOTE: uncomment the following line to make JsonArray and JsonObject class internal.
//#define SIMPLE_JSON_OBJARRAYINTERNAL
// NOTE: uncomment the following line to enable dynamic support.
//#define SIMPLE_JSON_DYNAMIC
////NOTE: uncomment the following line to make ReflectionUtils class public.
//#define SIMPLE_JSON_REFLECTION_UTILS_PUBLIC
//// NOTE: uncomment the following line to enable DataContract support.
#define SIMPLE_JSON_DATACONTRACT
//// NOTE: uncomment the following line to enable IReadOnlyCollection<T> and IReadOnlyList<T> support.
//#define SIMPLE_JSON_READONLY_COLLECTIONS
//// NOTE: uncomment the following line if you are compiling under Window Metro style application/library.
//// usually already defined in properties
////#define NETFX_CORE;
////NOTE:If you are targetting WinStore, WP8 and NET4.5+ PCL make sure to #define SIMPLE_JSON_TYPEINFO;
////#define SIMPLE_JSON_TYPEINFO
//// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
//NOTE:SIMPLE_JSON_NO_REFLECTION_ENUM_PARSE
//#define SIMPLE_JSON_NO_REFLECTION_ENUM_PARSE
//NOTE:#define SIMPLE_JSON_PFPARSE_IGNORE_LOWERCASE, Ignore the case of property/field names during deserialization
// Define to make the default serialization strategy ignore
// property/field name casing during deserialization.
// Serialization always preserves original casing.
// Equivalent to setting DefaultJsonSerializationStrategy.ignoreLowerCaseForDeserialization = true.
//
#define SIMPLE_JSON_PFPARSE_IGNORE_LOWERCASE
#if NET20
#undef SIMPLE_JSON_DATACONTRACT
#endif
#if NET20 || NET35 || NET40
#undef SIMPLE_JSON_READONLY_COLLECTIONS
#undef SIMPLE_JSON_AOT
#endif
//NOTE:.NET Framework not support AOT
#if NET45 || NET46 || NET46 || NET47 || NET48
#undef SIMPLE_JSON_AOT
#endif
//#if NETFX_CORE
//#define SIMPLE_JSON_TYPEINFO
//#endif
//#define SIMPLE_JSON_UNITY
//#define SIMPLE_JSON_WEBGL
//NOTE:Unity support
#if SIMPLE_JSON_UNITY
using UnityEngine;
#endif
// NET20
// Automatically defined by .NET 2.0 target framework.
// Disables ReaderWriterLockSlim (unavailable in .NET 2.0).
//
// UNITY_EDITOR, DEVELOPMENT_BUILD, DEBUG
// Enable Guard.LogWarning / Guard.LogError output and
// additional runtime validation. All diagnostic calls and
// their string arguments are compiled out in Release builds
// (zero overhead).
// ============================================================
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Text;
#if SIMPLE_JSON_UNITY
using UnityEngine;
//#endif
namespace UnityEngine {
}
#endif
namespace RS.SimpleJsonUnity
{
#region .NET 2.0
#if NET20
// All these delegate are built-in .NET 3.5
// Comment/Remove them when compiling to .NET 3.5 to avoid ambiguity.
public delegate void Action();
//public delegate void Action<T>(T arg);
public delegate void Action<T1, T2>(T1 arg1,T2 arg2);
public delegate void Action<T1, T2, T3>(T1 arg1,T2 arg2,T3 arg3);
//public delegate void Action<T1, T2, T3, T4>(T1 arg1,T2 arg2,T3 arg3,T4 arg4);
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg);
//public delegate TResult Func<T1, T2, TResult>(T1 arg1,T2 arg2);
//public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1,T2 arg2,T3 arg3);
//public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1,T2 arg2,T3 arg3,T4 arg4);
#elif NET35
#endif
#endregion
// ──────────────────────────────────────────────────────────────
// Attributes
// ──────────────────────────────────────────────────────────────
#region Attributes
[AttributeUsage(
AttributeTargets.Property | AttributeTargets.Field,
Inherited = true,AllowMultiple = false)]
public sealed class JsonIgnoreAttribute : Attribute { }
[AttributeUsage(
AttributeTargets.Property | AttributeTargets.Field,
Inherited = true,AllowMultiple = false)]
public sealed class JsonIncludeAttribute : Attribute { }
[AttributeUsage(
AttributeTargets.Property | AttributeTargets.Field,
Inherited = true,AllowMultiple = false)]
public sealed class JsonAliasAttribute : Attribute
{
public string[] Aliases { get; private set; }
public bool AcceptOriginalName { get; private set; }
public JsonAliasAttribute(params string[] aliases)
{
if (aliases == null) throw new ArgumentNullException("aliases");
if (aliases.Length == 0) throw new ArgumentException("At least one alias is required.","aliases");
Aliases = aliases;
AcceptOriginalName = true;
}
public JsonAliasAttribute(bool acceptOriginalName,params string[] aliases)
{
if (aliases == null) throw new ArgumentNullException("aliases");
if (aliases.Length == 0) throw new ArgumentException("At least one alias is required.","aliases");
Aliases = aliases;
AcceptOriginalName = acceptOriginalName;
}
[Obsolete("Use Aliases property instead. This property returns the first alias for backward compatibility.")]
public string Alias
{
get { return Aliases != null && Aliases.Length > 0 ? Aliases[0] : null; }
}
}
#endregion
static class Constants
{
/// <summary>
/// 日期时间的 ISO 8601 格式字符串数组,包含多种常见变体以提高兼容性。
/// </summary>
internal static readonly string[] Iso8601Format = new string[]
{
@"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
@"yyyy-MM-dd\THH:mm:ss.FFFFFFFK",
@"yyyy-MM-dd\THH:mm:ss\Z",
@"yyyy-MM-dd\THH:mm:ssK"
};
}
// ──────────────────────────────────────────────────────────────
// Guard
// ──────────────────────────────────────────────────────────────
#region Guard
internal static class Guard
{
public static void ArgumentNotNull(object argument,string argumentName)
{
if (argument == null)
throw new ArgumentNullException(argumentName);
}
public static void LogWarning(string message)
{
#if !(UNITY_EDITOR || DEVELOPMENT_BUILD || DEBUG)
return;
#endif
#if UNITY_EDITOR || DEVELOPMENT_BUILD
UnityEngine.Debug.LogWarning("[SimpleJson] " + message);
#elif DEBUG
Console.WriteLine("[SimpleJson] " + message);
#endif
}
public static void LogError(string message)
{
#if !(UNITY_EDITOR || DEVELOPMENT_BUILD || DEBUG)
return;
#endif
#if UNITY_EDITOR || DEVELOPMENT_BUILD
UnityEngine.Debug.LogError("[SimpleJson] " + message);
#elif DEBUG
Console.WriteLine("[SimpleJson] ERROR: " + message);
#endif
}
}
#endregion
// ──────────────────────────────────────────────────────────────
// TypeCacheKey (缓存复合 key,区分 ignoreLowerCaseDeserialization 和 useJsonAlias 状态)
// ──────────────────────────────────────────────────────────────
#region TypeCacheKey
public struct TypeCacheKey : IEquatable<TypeCacheKey>
{
public readonly Type Type;
public readonly bool IgnoreLowerCase;
public readonly bool UseJsonAlias;
public TypeCacheKey(Type type,bool ignoreLowerCase)
{
Type = type;
IgnoreLowerCase = ignoreLowerCase;
UseJsonAlias = false;
}
public TypeCacheKey(Type type,bool ignoreLowerCase,bool useJsonAlias)
{
Type = type;
IgnoreLowerCase = ignoreLowerCase;
UseJsonAlias = useJsonAlias;
}
public bool Equals(TypeCacheKey other)
{
return Type == other.Type
&& IgnoreLowerCase == other.IgnoreLowerCase
&& UseJsonAlias == other.UseJsonAlias;
}
public override bool Equals(object obj)
{
if (!(obj is TypeCacheKey)) return false;
return Equals((TypeCacheKey)obj);
}
public override int GetHashCode()
{
unchecked
{
int h = (Type != null ? Type.GetHashCode() : 0);
h ^= IgnoreLowerCase.GetHashCode();
h = (h * 397) ^ UseJsonAlias.GetHashCode();
return h;
}
}
}
#endregion
#if NET20
/// <summary>
/// .NET 2.0 兼容的简易 HashSet<T>(核心功能:唯一元素、添加/移除/包含判断、遍历)
/// </summary>
/// <typeparam name="T">元素类型</typeparam>
public class HashSet<T> : IEnumerable<T>
{
// 底层存储:利用 Dictionary 的键唯一性
private readonly Dictionary<T,object> _dictionary;
// 占位值(复用一个对象,减少内存分配)
private static readonly object _placeholder = new object();
/// <summary>
/// 初始化空的 HashSet
/// </summary>
public HashSet()
{
_dictionary = new Dictionary<T,object>();
}
/// <summary>
/// 初始化并添加初始集合
/// </summary>
/// <param name="collection">初始元素集合</param>
public HashSet(IEnumerable<T> collection)
{
_dictionary = new Dictionary<T,object>();
foreach (T item in collection)
{
Add(item);
}
}
/// <summary>
/// 获取集合中元素的数量
/// </summary>
public int Count
{
get { return _dictionary.Count; }
}
/// <summary>
/// 添加元素(符合官方设计:新增成功返回 true,已存在返回 false)
/// </summary>
/// <param name="item">要添加的元素</param>
/// <returns>添加成功返回 true,元素已存在返回 false</returns>
public bool Add(T item)
{
if (_dictionary.ContainsKey(item))
{
return false; // 元素已存在,添加失败
}
_dictionary.Add(item,_placeholder);
return true; // 元素新增成功
}
/// <summary>
/// 移除元素(不存在则忽略)
/// </summary>
/// <param name="item">要移除的元素</param>
public void Remove(T item)
{
_dictionary.Remove(item);
}
/// <summary>
/// 判断元素是否存在
/// </summary>
/// <param name="item">要检查的元素</param>
/// <returns>存在返回 true,否则 false</returns>
public bool Contains(T item)
{
return _dictionary.ContainsKey(item);
}
/// <summary>
/// 清空所有元素
/// </summary>
public void Clear()
{
_dictionary.Clear();
}
/// <summary>
/// 实现枚举器,支持 foreach 遍历
/// </summary>
/// <returns>元素枚举器</returns>
public IEnumerator<T> GetEnumerator()
{
// 遍历 Dictionary 的键(即 HashSet 的元素)
foreach (T key in _dictionary.Keys)
{
yield return key;
}
}
/// <summary>
/// 非泛型枚举器(IEnumerable 接口实现)
/// </summary>
/// <returns>非泛型枚举器</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
#endif
// ──────────────────────────────────────────────────────────────
// ThreadSafeDictionary
// ──────────────────────────────────────────────────────────────
#region ThreadSafeDictionary
public sealed class ThreadSafeDictionary<TKey, TValue>
: IDictionary<TKey,TValue>
{
private readonly Dictionary<TKey,TValue> _dict =
new Dictionary<TKey,TValue>();
#if SIMPLE_JSON_WEBGL
// WebGL 单线程:完全无锁,零开销
public TValue this[TKey key]
{
get { return _dict[key]; }
set { _dict[key] = value; }
}
public bool TryGetValue(TKey key,out TValue value)
{
return _dict.TryGetValue(key,out value);
}
public bool ContainsKey(TKey key)
{
return _dict.ContainsKey(key);
}
public void Add(TKey key,TValue value)
{
_dict[key] = value;
}
public bool Remove(TKey key)
{
return _dict.Remove(key);
}
public void Clear()
{
_dict.Clear();
}
public int Count
{
get { return _dict.Count; }
}
public ICollection<TKey> Keys
{
get { return new List<TKey>(_dict.Keys); }
}
public ICollection<TValue> Values
{
get { return new List<TValue>(_dict.Values); }
}
public IEnumerator<KeyValuePair<TKey,TValue>> GetEnumerator()
{
return new List<KeyValuePair<TKey,TValue>>(_dict).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
#elif NET20 || SIMPLE_JSON_UNITY
private readonly object _lock = new object();
public TValue this[TKey key]
{
get { lock (_lock) { return _dict[key]; } }
set { lock (_lock) { _dict[key] = value; } }
}
public bool TryGetValue(TKey key,out TValue value)
{
lock (_lock) { return _dict.TryGetValue(key,out value); }
}
public bool ContainsKey(TKey key)
{
lock (_lock) { return _dict.ContainsKey(key); }
}
public void Add(TKey key,TValue value)
{
lock (_lock) { _dict[key] = value; }
}
public bool Remove(TKey key)
{
lock (_lock) { return _dict.Remove(key); }
}
public void Clear()
{
lock (_lock) { _dict.Clear(); }
}
public int Count
{
get { lock (_lock) { return _dict.Count; } }
}
public ICollection<TKey> Keys
{
get { lock (_lock) { return new List<TKey>(_dict.Keys); } }
}
public ICollection<TValue> Values
{
get { lock (_lock) { return new List<TValue>(_dict.Values); } }
}
public IEnumerator<KeyValuePair<TKey,TValue>> GetEnumerator()
{
List<KeyValuePair<TKey,TValue>> snapshot;
lock (_lock)
{
snapshot = new List<KeyValuePair<TKey,TValue>>(_dict);
}
return snapshot.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
#else
private readonly System.Threading.ReaderWriterLockSlim _lock =
new System.Threading.ReaderWriterLockSlim();
public TValue this[TKey key]
{
get
{
_lock.EnterReadLock();
try { return _dict[key]; }
finally { _lock.ExitReadLock(); }
}
set
{
_lock.EnterWriteLock();
try { _dict[key] = value; }
finally { _lock.ExitWriteLock(); }
}
}
public bool TryGetValue(TKey key,out TValue value)
{
_lock.EnterReadLock();
try { return _dict.TryGetValue(key,out value); }
finally { _lock.ExitReadLock(); }
}
public bool ContainsKey(TKey key)
{
_lock.EnterReadLock();
try { return _dict.ContainsKey(key); }
finally { _lock.ExitReadLock(); }
}
public void Add(TKey key,TValue value)
{
_lock.EnterWriteLock();
try { _dict[key] = value; }
finally { _lock.ExitWriteLock(); }
}
public bool Remove(TKey key)
{
_lock.EnterWriteLock();
try { return _dict.Remove(key); }
finally { _lock.ExitWriteLock(); }
}
public void Clear()
{
_lock.EnterWriteLock();
try { _dict.Clear(); }
finally { _lock.ExitWriteLock(); }
}
public int Count
{
get
{
_lock.EnterReadLock();
try { return _dict.Count; }
finally { _lock.ExitReadLock(); }
}
}
public ICollection<TKey> Keys
{
get
{
_lock.EnterReadLock();
try { return new List<TKey>(_dict.Keys); }
finally { _lock.ExitReadLock(); }
}
}
public ICollection<TValue> Values
{
get
{
_lock.EnterReadLock();
try { return new List<TValue>(_dict.Values); }
finally { _lock.ExitReadLock(); }
}
}
public IEnumerator<KeyValuePair<TKey,TValue>> GetEnumerator()
{
List<KeyValuePair<TKey,TValue>> snapshot;
_lock.EnterReadLock();
try { snapshot = new List<KeyValuePair<TKey,TValue>>(_dict); }
finally { _lock.ExitReadLock(); }
return snapshot.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
#endif
// ICollection<KVP> 接口实现
public bool IsReadOnly { get { return false; } }
public void Add(KeyValuePair<TKey,TValue> item)
{
Add(item.Key,item.Value);
}
public bool Contains(KeyValuePair<TKey,TValue> item)
{
TValue val;
if (!TryGetValue(item.Key,out val)) return false;
return EqualityComparer<TValue>.Default.Equals(val,item.Value);
}
public void CopyTo(KeyValuePair<TKey,TValue>[] array,int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException("arrayIndex");
// 快照后检查边界,避免锁内抛异常
List<KeyValuePair<TKey,TValue>> snapshot =
new List<KeyValuePair<TKey,TValue>>(this);
if (array.Length - arrayIndex < snapshot.Count)
throw new ArgumentException(
"Destination array is not long enough.");
for (int i = 0; i < snapshot.Count; i++)
array[arrayIndex + i] = snapshot[i];
}
public bool Remove(KeyValuePair<TKey,TValue> item)
{
TValue val;
if (!TryGetValue(item.Key,out val)) return false;
if (!EqualityComparer<TValue>.Default.Equals(val,item.Value))
return false;
return Remove(item.Key);
}
}
#endregion
// ──────────────────────────────────────────────────────────────
// ReflectionUtils
// ──────────────────────────────────────────────────────────────
#region ReflectionUtils
[GeneratedCode("reflection-utils","1.0.0")]
#if SIMPLE_JSON_REFLECTION_UTILS_PUBLIC
public
#else
public
#endif
static class ReflectionUtils
{
public const BindingFlags PUBLIC_INSTANCE = BindingFlags.Public | BindingFlags.Instance;
public const BindingFlags NONPUBLIC_INSTANCE = BindingFlags.NonPublic | BindingFlags.Instance;
// ── Attribute 辅助 ──────────────────────────────────────────
public static bool HasAttribute<T>(MemberInfo member) where T : Attribute
{
return member.GetCustomAttributes(typeof(T),true).Length > 0;
}
public static T GetAttribute<T>(MemberInfo member) where T : Attribute
{
object[] attrs = member.GetCustomAttributes(typeof(T),true);
return attrs.Length > 0 ? (T)attrs[0] : null;
}
public static string GetFirstAlias(JsonAliasAttribute aliasAttr)
{
if (aliasAttr != null && aliasAttr.Aliases != null && aliasAttr.Aliases.Length > 0)
return aliasAttr.Aliases[0];
return null;
}
public static Attribute GetAttribute(MemberInfo info,Type type)
{
#if SIMPLE_JSON_TYPEINFO
if (info == null || type == null || !info.IsDefined(type))
return null;
return info.GetCustomAttribute(type);
#else
if (info == null || type == null || !Attribute.IsDefined(info,type))
return null;
return Attribute.GetCustomAttribute(info,type);
#endif
}
public static Attribute GetAttribute(Type objectType,Type attributeType)
{
#if SIMPLE_JSON_TYPEINFO
if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType))
return null;
return objectType.GetTypeInfo().GetCustomAttribute(attributeType);
#else
if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType,attributeType))
return null;
return Attribute.GetCustomAttribute(objectType,attributeType);
#endif
}
// ── SIMPLE_JSON_TYPEINFO 支持 ─────────────────────────────
#if SIMPLE_JSON_TYPEINFO
public static System.Reflection.TypeInfo GetTypeInfo(Type type)
{
return type.GetTypeInfo();
}
#else
public static Type GetTypeInfo(Type type)
{
return type;
}
#endif
public static bool IsTypeGeneric(Type type)
{
return GetTypeInfo(type).IsGenericType;
}
public static bool IsAssignableFrom(Type type1,Type type2)
{
return GetTypeInfo(type1).IsAssignableFrom(GetTypeInfo(type2));
}
public static Type[] GetGenericTypeArguments(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetTypeInfo().GenericTypeArguments;
#else
return type.GetGenericArguments();
#endif
}
public static IEnumerable<Type> GetImplementedInterfaces(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetTypeInfo().ImplementedInterfaces;
#else
return type.GetInterfaces();
#endif
}
// ── 类型判断 ─────────────────────────────────────────────
public static bool IsTypeGenericeCollectionInterface(Type type)
{
if (!IsTypeGeneric(type))
return false;
Type genericDefinition = type.GetGenericTypeDefinition();
return (genericDefinition == typeof(IList<>)
|| genericDefinition == typeof(ICollection<>)
|| genericDefinition == typeof(IEnumerable<>)
#if SIMPLE_JSON_READONLY_COLLECTIONS
|| genericDefinition == typeof(IReadOnlyCollection<>)
|| genericDefinition == typeof(IReadOnlyList<>)
#endif
);
}
public static bool IsTypeDictionary(Type type)
{
// 非泛型 IDictionary(Hashtable、SortedList 等)
#if SIMPLE_JSON_TYPEINFO
if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
return true;
#else
if (typeof(System.Collections.IDictionary).IsAssignableFrom(type))
return true;
#endif
// 泛型 IDictionary<,>(Dictionary<K,V>、SortedDictionary<K,V> 等)
foreach (Type iface in GetImplementedInterfaces(type))
{
if (iface.IsGenericType)
{
Type genericDef = iface.GetGenericTypeDefinition();
if (genericDef == typeof(IDictionary<,>)
#if SIMPLE_JSON_READONLY_COLLECTIONS
|| genericDef == typeof(IReadOnlyDictionary<,>)
#endif
)
return true;
}
}
return false;
}
public static bool IsNullableType(Type type)
{
return Nullable.GetUnderlyingType(type) != null;
//return GetTypeInfo(type).IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
}
public static object ToNullableType(object obj,Type nullableType)
{
return obj == null ? null : Convert.ChangeType(obj,Nullable.GetUnderlyingType(nullableType),CultureInfo.InvariantCulture);
}
public static Type GetGenericListElementType(Type type)
{
foreach (Type implementedInterface in GetImplementedInterfaces(type))
{
if (IsTypeGeneric(implementedInterface) &&
implementedInterface.GetGenericTypeDefinition() == typeof(IList<>))
{
return GetGenericTypeArguments(implementedInterface)[0];
}
}
return GetGenericTypeArguments(type)[0];
}
public static IEnumerable<PropertyInfo> GetProperties(Type type,BindingFlags bindingAttr)
{
#if SIMPLE_JSON_TYPEINFO
var result = new List<PropertyInfo>();
foreach (PropertyInfo p in type.GetRuntimeProperties())
{
MethodInfo m = p.GetMethod;
if (m == null) m = p.SetMethod;
if (m == null) continue;
bool match = true;
if ((bindingAttr & BindingFlags.Public) != 0 && !m.IsPublic) match = false;
if ((bindingAttr & BindingFlags.NonPublic) != 0 && m.IsPublic) match = false;
if ((bindingAttr & BindingFlags.Static) != 0 && !m.IsStatic) match = false;
if ((bindingAttr & BindingFlags.Instance) != 0 && m.IsStatic) match = false;
if (match) result.Add(p);
}
return result;
#else
return type.GetProperties(bindingAttr);
#endif
}
public static IEnumerable<FieldInfo> GetFields(Type type,BindingFlags bindingAttr)
{
#if SIMPLE_JSON_TYPEINFO
var result = new List<FieldInfo>();
foreach (FieldInfo f in type.GetRuntimeFields())
{
bool match = true;
if ((bindingAttr & BindingFlags.Public) != 0 && !f.IsPublic) match = false;
if ((bindingAttr & BindingFlags.NonPublic) != 0 && f.IsPublic) match = false;
if ((bindingAttr & BindingFlags.Static) != 0 && !f.IsStatic) match = false;
if ((bindingAttr & BindingFlags.Instance) != 0 && f.IsStatic) match = false;
if (match) result.Add(f);
}
return result;
#else
return type.GetFields(bindingAttr);
#endif
}
public static MethodInfo GetGetterMethod(PropertyInfo property)
{
#if SIMPLE_JSON_TYPEINFO
return property.GetMethod;
#else
return property.GetGetMethod(true);
#endif
}
public static MethodInfo GetSetterMethod(PropertyInfo property)
{
#if SIMPLE_JSON_TYPEINFO
return property.SetMethod;
#else
return property.GetSetMethod(true);
#endif
}
public static bool IsValueType(Type type)
{
return GetTypeInfo(type).IsValueType;
}
//-------------------------------------
#region GetSetDelegate
public delegate object GetDelegate(object source);
public delegate void SetDelegate(object source,object value);
public static GetDelegate GetGetMethod(PropertyInfo propertyInfo)
{
return GetGetMethodByReflection(propertyInfo);
}
public static GetDelegate GetGetMethod(FieldInfo fieldInfo)
{
return GetGetMethodByReflection(fieldInfo);
}
public static GetDelegate GetGetMethodByReflection(PropertyInfo propertyInfo)
{
MethodInfo methodInfo = GetGetterMethodInfo(propertyInfo);
return delegate (object source) { return methodInfo.Invoke(source,EmptyObjects); };
}
public static GetDelegate GetGetMethodByReflection(FieldInfo fieldInfo)
{
return delegate (object source) { return fieldInfo.GetValue(source); };
}
public static SetDelegate GetSetMethod(PropertyInfo propertyInfo)
{
return GetSetMethodByReflection(propertyInfo);
}
public static SetDelegate GetSetMethod(FieldInfo fieldInfo)
{
return GetSetMethodByReflection(fieldInfo);
}
public static SetDelegate GetSetMethodByReflection(PropertyInfo propertyInfo)
{
MethodInfo methodInfo = GetSetterMethodInfo(propertyInfo);
return delegate (object source,object value) { methodInfo.Invoke(source,new object[] { value }); };
}
public static SetDelegate GetSetMethodByReflection(FieldInfo fieldInfo)
{
return delegate (object source,object value) { fieldInfo.SetValue(source,value); };
}
static readonly object[] EmptyObjects = new object[] { };
#endregion
#region 构造器
public static IEnumerable<ConstructorInfo> GetConstructors(Type type)
{
#if SIMPLE_JSON_TYPEINFO
return type.GetTypeInfo().DeclaredConstructors;
#else
return type.GetConstructors();
#endif
}
public static MethodInfo GetGetterMethodInfo(PropertyInfo propertyInfo)
{
#if SIMPLE_JSON_TYPEINFO
return propertyInfo.GetMethod;
#else
return propertyInfo.GetGetMethod(true);
#endif
}
public static MethodInfo GetSetterMethodInfo(PropertyInfo propertyInfo)
{
#if SIMPLE_JSON_TYPEINFO
return propertyInfo.SetMethod;
#else
return propertyInfo.GetSetMethod(true);
#endif
}
public static ConstructorDelegate GetContructor(ConstructorInfo constructorInfo)
{
return GetConstructorByReflection(constructorInfo);
}
public static ConstructorDelegate GetContructor(Type type,params Type[] argsType)
{
return GetConstructorByReflection(type,argsType);
}
public static ConstructorDelegate GetConstructorByReflection(ConstructorInfo constructorInfo)
{
return delegate (object[] args) { return constructorInfo.Invoke(args); };
}
public static ConstructorDelegate GetConstructorByReflection(Type type,params Type[] argsType)
{
ConstructorInfo constructorInfo = GetConstructorInfo(type,argsType);
// if it's a value type (i.e., struct), it won't have a default constructor, so use Activator instead
return constructorInfo == null ? (type.IsValueType ? GetConstructorForValueType(type) : null) : GetConstructorByReflection(constructorInfo);
}
static ConstructorDelegate GetConstructorForValueType(Type type)
{
return delegate (object[] args) { return Activator.CreateInstance(type); };
}
public static ConstructorInfo GetConstructorInfo(Type type,params Type[] argsType)
{
IEnumerable<ConstructorInfo> constructorInfos = GetConstructors(type);
int i;
bool matches;
foreach (ConstructorInfo constructorInfo in constructorInfos)
{
ParameterInfo[] parameters = constructorInfo.GetParameters();
if (argsType.Length != parameters.Length)
continue;
i = 0;
matches = true;
foreach (ParameterInfo parameterInfo in constructorInfo.GetParameters())
{
if (parameterInfo.ParameterType != argsType[i])
{
matches = false;
break;
}
}
if (matches)
return constructorInfo;
}
return null;
}
#endregion
//---构造函数-----------------------------
public delegate object ConstructorDelegate(params object[] args);