forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsConfig.cs
More file actions
495 lines (436 loc) · 16.4 KB
/
JsConfig.cs
File metadata and controls
495 lines (436 loc) · 16.4 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
using System;
using System.Collections.Generic;
using System.IO;
using ServiceStack.Text.Common;
#if WINDOWS_PHONE
using ServiceStack.Text.WP;
#endif
namespace ServiceStack.Text
{
public static class
JsConfig
{
static JsConfig()
{
//In-built default serialization, to Deserialize Color struct do:
//JsConfig<System.Drawing.Color>.SerializeFn = c => c.ToString().Replace("Color ", "").Replace("[", "").Replace("]", "");
//JsConfig<System.Drawing.Color>.DeSerializeFn = System.Drawing.Color.FromName;
Reset();
}
[ThreadStatic]
private static bool? tsConvertObjectTypesIntoStringDictionary;
private static bool? sConvertObjectTypesIntoStringDictionary;
public static bool ConvertObjectTypesIntoStringDictionary
{
get
{
return tsConvertObjectTypesIntoStringDictionary ?? sConvertObjectTypesIntoStringDictionary ?? false;
}
set
{
tsConvertObjectTypesIntoStringDictionary = value;
if (!sConvertObjectTypesIntoStringDictionary.HasValue) sConvertObjectTypesIntoStringDictionary = value;
}
}
[ThreadStatic]
private static bool? tsIncludeNullValues;
private static bool? sIncludeNullValues;
public static bool IncludeNullValues
{
get
{
return tsIncludeNullValues ?? sIncludeNullValues ?? false;
}
set
{
tsIncludeNullValues = value;
if (!sIncludeNullValues.HasValue) sIncludeNullValues = value;
}
}
[ThreadStatic]
private static bool? tsExcludeTypeInfo;
private static bool? sExcludeTypeInfo;
public static bool ExcludeTypeInfo
{
get
{
return tsExcludeTypeInfo ?? sExcludeTypeInfo ?? false;
}
set
{
tsExcludeTypeInfo = value;
if (!sExcludeTypeInfo.HasValue) sExcludeTypeInfo = value;
}
}
[ThreadStatic]
private static JsonDateHandler? tsDateHandler;
private static JsonDateHandler? sDateHandler;
public static JsonDateHandler DateHandler
{
get
{
return tsDateHandler ?? sDateHandler ?? JsonDateHandler.TimestampOffset;
}
set
{
tsDateHandler = value;
if (!sDateHandler.HasValue) sDateHandler = value;
}
}
/// <summary>
/// Sets which format to use when serializing TimeSpans
/// </summary>
public static JsonTimeSpanHandler TimeSpanHandler { get; set; }
/// <summary>
/// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured
/// to take advantage of <see cref="CLSCompliantAttribute"/> specification,
/// to support user-friendly serialized formats, ie emitting camelCasing for JSON
/// and parsing member names and enum values in a case-insensitive manner.
/// </summary>
[ThreadStatic]
private static bool? tsEmitCamelCaseNames;
private static bool? sEmitCamelCaseNames;
public static bool EmitCamelCaseNames
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return tsEmitCamelCaseNames ?? sEmitCamelCaseNames ?? false;
}
set
{
tsEmitCamelCaseNames = value;
if (!sEmitCamelCaseNames.HasValue) sEmitCamelCaseNames = value;
}
}
/// <summary>
/// Gets or sets a value indicating if the framework should throw serialization exceptions
/// or continue regardless of deserialization errors. If <see langword="true"/> the framework
/// will throw; otherwise, it will parse as many fields as possible. The default is <see langword="false"/>.
/// </summary>
[ThreadStatic]
private static bool? tsThrowOnDeserializationError;
private static bool? sThrowOnDeserializationError;
public static bool ThrowOnDeserializationError
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return tsThrowOnDeserializationError ?? sThrowOnDeserializationError ?? false;
}
set
{
tsThrowOnDeserializationError = value;
if (!sThrowOnDeserializationError.HasValue) sThrowOnDeserializationError = value;
}
}
internal static HashSet<Type> HasSerializeFn = new HashSet<Type>();
internal static HashSet<Type> TreatValueAsRefTypes = new HashSet<Type>();
[ThreadStatic]
private static bool? tsPreferInterfaces;
private static bool? sPreferInterfaces;
/// <summary>
/// If set to true, Interface types will be prefered over concrete types when serializing.
/// </summary>
public static bool PreferInterfaces
{
get
{
return tsPreferInterfaces ?? sPreferInterfaces ?? false;
}
set
{
tsPreferInterfaces = value;
if (!sPreferInterfaces.HasValue) sPreferInterfaces = value;
}
}
internal static bool TreatAsRefType(Type valueType)
{
return TreatValueAsRefTypes.Contains(valueType.IsGenericType ? valueType.GetGenericTypeDefinition() : valueType);
}
public static void Reset()
{
tsConvertObjectTypesIntoStringDictionary = sConvertObjectTypesIntoStringDictionary = null;
tsIncludeNullValues = sIncludeNullValues = null;
tsExcludeTypeInfo = sExcludeTypeInfo = null;
tsEmitCamelCaseNames = sEmitCamelCaseNames = null;
tsDateHandler = sDateHandler = null;
tsPreferInterfaces = sPreferInterfaces = null;
tsThrowOnDeserializationError = sThrowOnDeserializationError = null;
HasSerializeFn = new HashSet<Type>();
TreatValueAsRefTypes = new HashSet<Type> {
typeof(KeyValuePair<,>)
};
}
#if MONOTOUCH
/// <summary>
/// Provide hint to MonoTouch AOT compiler to pre-compile generic classes for all your DTOs.
/// Just needs to be called once in a static constructor.
/// </summary>
[MonoTouch.Foundation.Preserve]
public static void InitForAot() { }
[MonoTouch.Foundation.Preserve]
public static void RegisterForAot()
{
JsonAotConfig.Register<Poco>();
RegisterElement<Poco, string>();
RegisterElement<Poco, bool>();
RegisterElement<Poco, char>();
RegisterElement<Poco, byte>();
RegisterElement<Poco, sbyte>();
RegisterElement<Poco, short>();
RegisterElement<Poco, ushort>();
RegisterElement<Poco, int>();
RegisterElement<Poco, uint>();
RegisterElement<Poco, long>();
RegisterElement<Poco, ulong>();
RegisterElement<Poco, float>();
RegisterElement<Poco, double>();
RegisterElement<Poco, decimal>();
RegisterElement<Poco, Guid>();
RegisterElement<Poco, DateTime>();
RegisterElement<Poco, TimeSpan>();
RegisterElement<Poco, bool?>();
RegisterElement<Poco, char?>();
RegisterElement<Poco, byte?>();
RegisterElement<Poco, sbyte?>();
RegisterElement<Poco, short?>();
RegisterElement<Poco, ushort?>();
RegisterElement<Poco, int?>();
RegisterElement<Poco, uint?>();
RegisterElement<Poco, long?>();
RegisterElement<Poco, ulong?>();
RegisterElement<Poco, float?>();
RegisterElement<Poco, double?>();
RegisterElement<Poco, decimal?>();
RegisterElement<Poco, Guid?>();
RegisterElement<Poco, DateTime?>();
RegisterElement<Poco, TimeSpan?>();
RegisterQueryStringWriter();
RegisterCsvSerializer();
}
[MonoTouch.Foundation.Preserve]
public static bool RegisterTypeForAot<T>()
{
bool ret = false;
try
{
JsonAotConfig.Register<T>();
int i = 0;
if(JsvWriter<T>.WriteFn() != null && JsvReader<T>.GetParseFn() != null) i++;
if(JsonWriter<T>.WriteFn() != null && JsonReader<T>.GetParseFn() != null) i++;
if(QueryStringWriter<Poco>.WriteFn() != null) i++;
CsvSerializer<T>.WriteFn();
CsvSerializer<T>.WriteObject(null, null);
CsvWriter<T>.WriteObject(null, null);
CsvWriter<T>.WriteObjectRow(null, null);
ret = true;
}catch(Exception){}
return ret;
}
[MonoTouch.Foundation.Preserve]
static void RegisterQueryStringWriter()
{
var i = 0;
if (QueryStringWriter<Poco>.WriteFn() != null) i++;
}
[MonoTouch.Foundation.Preserve]
static void RegisterCsvSerializer()
{
CsvSerializer<Poco>.WriteFn();
CsvSerializer<Poco>.WriteObject(null, null);
CsvWriter<Poco>.WriteObject(null, null);
CsvWriter<Poco>.WriteObjectRow(null, null);
}
[MonoTouch.Foundation.Preserve]
public static void RegisterElement<T, TElement>()
{
JsonAotConfig.RegisterElement<T, TElement>();
}
#endif
}
#if MONOTOUCH
[MonoTouch.Foundation.Preserve(AllMembers=true)]
internal class Poco
{
public string Dummy { get; set; }
}
[MonoTouch.Foundation.Preserve(AllMembers=true)]
internal class JsonAotConfig
{
static JsReader<JsonTypeSerializer> reader;
static JsWriter<JsonTypeSerializer> writer;
static JsonTypeSerializer serializer;
static JsonAotConfig()
{
serializer = new JsonTypeSerializer();
reader = new JsReader<JsonTypeSerializer>();
writer = new JsWriter<JsonTypeSerializer>();
}
public static ParseStringDelegate GetParseFn(Type type)
{
var parseFn = JsonTypeSerializer.Instance.GetParseFn(type);
return parseFn;
}
internal static ParseStringDelegate RegisterBuiltin<T>()
{
var i = 0;
if (reader.GetParseFn<T>() != null) i++;
if (JsonReader<T>.GetParseFn() != null) i++;
if (JsonReader<T>.Parse(null) != null) i++;
if (JsonWriter<T>.WriteFn() != null) i++;
return serializer.GetParseFn<T>();
}
public static void Register<T>()
{
var i = 0;
var serializer = JsonTypeSerializer.Instance;
if (new List<T>() != null) i++;
if (new T[0] != null) i++;
if (serializer.GetParseFn<T>() != null) i++;
if (DeserializeArray<T[], JsonTypeSerializer>.Parse != null) i++;
JsConfig<T>.ExcludeTypeInfo = false;
//JsConfig<T>.SerializeFn = arg => "";
//JsConfig<T>.DeSerializeFn = arg => default(T);
DeserializeArrayWithElements<T, JsonTypeSerializer>.ParseGenericArray(null, null);
DeserializeCollection<JsonTypeSerializer>.ParseCollection<T>(null, null, null);
DeserializeListWithElements<T, JsonTypeSerializer>.ParseGenericList(null, null, null);
SpecializedQueueElements<T>.ConvertToQueue(null);
SpecializedQueueElements<T>.ConvertToStack(null);
WriteListsOfElements<T, JsonTypeSerializer>.WriteList(null, null);
WriteListsOfElements<T, JsonTypeSerializer>.WriteIList(null, null);
WriteListsOfElements<T, JsonTypeSerializer>.WriteEnumerable(null, null);
WriteListsOfElements<T, JsonTypeSerializer>.WriteListValueType(null, null);
WriteListsOfElements<T, JsonTypeSerializer>.WriteIListValueType(null, null);
JsonReader<T>.Parse(null);
JsonWriter<T>.WriteFn();
TranslateListWithElements<T>.LateBoundTranslateToGenericICollection(null, null);
TranslateListWithConvertibleElements<T, T>.LateBoundTranslateToGenericICollection(null, null);
QueryStringWriter<T>.WriteObject(null, null);
}
// Edited to fix issues with null List<Guid> properties in response objects
public static void RegisterElement<T, TElement>()
{
RegisterBuiltin<TElement>();
DeserializeDictionary<JsonTypeSerializer>.ParseDictionary<T, TElement>(null, null, null, null);
DeserializeDictionary<JsonTypeSerializer>.ParseDictionary<TElement, T>(null, null, null, null);
ToStringDictionaryMethods<T, TElement, JsonTypeSerializer>.WriteIDictionary(null, null, null, null);
ToStringDictionaryMethods<TElement, T, JsonTypeSerializer>.WriteIDictionary(null, null, null, null);
// Include List deserialisations from the Register<> method above. This solves issue where List<Guid> properties on responses deserialise to null.
// No idea why this is happening because there is no visible exception raised. Suspect MonoTouch is swallowing an AOT exception somewhere.
DeserializeArrayWithElements<TElement, JsonTypeSerializer>.ParseGenericArray(null, null);
DeserializeListWithElements<TElement, JsonTypeSerializer>.ParseGenericList(null, null, null);
// Cannot use the line below for some unknown reason - when trying to compile to run on device, mtouch bombs during native code compile.
// Something about this line or its inner workings is offensive to mtouch. Luckily this was not needed for my List<Guide> issue.
// DeserializeCollection<JsonTypeSerializer>.ParseCollection<TElement>(null, null, null);
TranslateListWithElements<TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>));
TranslateListWithConvertibleElements<TElement, TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>));
}
}
#endif
public class JsConfig<T>
{
/// <summary>
/// Never emit type info for this type
/// </summary>
public static bool ExcludeTypeInfo = false;
/// <summary>
/// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured
/// to take advantage of <see cref="CLSCompliantAttribute"/> specification,
/// to support user-friendly serialized formats, ie emitting camelCasing for JSON
/// and parsing member names and enum values in a case-insensitive manner.
/// </summary>
public static bool EmitCamelCaseNames = false;
/// <summary>
/// Define custom serialization fn for BCL Structs
/// </summary>
private static Func<T, string> serializeFn;
public static Func<T, string> SerializeFn
{
get { return serializeFn; }
set
{
serializeFn = value;
if (value != null)
JsConfig.HasSerializeFn.Add(typeof(T));
else
JsConfig.HasSerializeFn.Remove(typeof(T));
}
}
/// <summary>
/// Opt-in flag to set some Value Types to be treated as a Ref Type
/// </summary>
public bool TreatValueAsRefTypes
{
get { return JsConfig.TreatValueAsRefTypes.Contains(typeof (T)); }
set
{
if (value)
JsConfig.TreatValueAsRefTypes.Add(typeof(T));
else
JsConfig.TreatValueAsRefTypes.Remove(typeof(T));
}
}
/// <summary>
/// Whether there is a fn (raw or otherwise)
/// </summary>
public static bool HasSerializeFn
{
get { return serializeFn != null || rawSerializeFn != null; }
}
/// <summary>
/// Define custom raw serialization fn
/// </summary>
private static Func<T, string> rawSerializeFn;
public static Func<T, string> RawSerializeFn
{
get { return rawSerializeFn; }
set
{
rawSerializeFn = value;
if (value != null)
JsConfig.HasSerializeFn.Add(typeof(T));
else
JsConfig.HasSerializeFn.Remove(typeof(T));
}
}
/// <summary>
/// Define custom deserialization fn for BCL Structs
/// </summary>
public static Func<string, T> DeSerializeFn;
/// <summary>
/// Exclude specific properties of this type from being serialized
/// </summary>
public static string[] ExcludePropertyNames;
public static void WriteFn<TSerializer>(TextWriter writer, object obj)
{
if (RawSerializeFn != null) {
writer.Write(RawSerializeFn((T)obj));
} else {
var serializer = JsWriter.GetTypeSerializer<TSerializer>();
serializer.WriteString(writer, SerializeFn((T)obj));
}
}
public static object ParseFn(string str)
{
return DeSerializeFn(str);
}
}
public enum JsonDateHandler
{
TimestampOffset,
DCJSCompatible,
ISO8601
}
public enum JsonTimeSpanHandler
{
/// <summary>
/// Uses the xsd format like PT15H10M20S
/// </summary>
DurationFormat,
/// <summary>
/// Uses the standard .net ToString method of the TimeSpan class
/// </summary>
StandardFormat
}
}