This repository was archived by the owner on Dec 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 614
Expand file tree
/
Copy pathWriteType.cs
More file actions
484 lines (425 loc) · 20 KB
/
WriteType.cs
File metadata and controls
484 lines (425 loc) · 20 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
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Reflection;
using ServiceStack.Text.Json;
using ServiceStack.Text.Reflection;
namespace ServiceStack.Text.Common
{
internal static class WriteType<T, TSerializer>
where TSerializer : ITypeSerializer
{
private const int DataMemberOrderNotSet = -1;
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
private static readonly WriteObjectDelegate CacheFn;
internal static TypePropertyWriter[] PropertyWriters;
private static readonly WriteObjectDelegate WriteTypeInfo;
private static bool IsIncluded
{
get { return (JsConfig.IncludeTypeInfo || JsConfig<T>.IncludeTypeInfo); }
}
private static bool IsExcluded
{
get { return (JsConfig.ExcludeTypeInfo || JsConfig<T>.ExcludeTypeInfo); }
}
static WriteType()
{
if (typeof(T) == typeof(Object))
{
CacheFn = WriteObjectType;
}
else
{
CacheFn = Init() ? GetWriteFn() : WriteEmptyType;
}
if (IsIncluded)
{
WriteTypeInfo = TypeInfoWriter;
}
if (typeof(T).IsAbstract())
{
WriteTypeInfo = TypeInfoWriter;
if (!JsConfig.PreferInterfaces || !typeof(T).IsInterface())
{
CacheFn = WriteAbstractProperties;
}
}
}
public static void TypeInfoWriter(TextWriter writer, object obj)
{
TryWriteTypeInfo(writer, obj);
}
private static bool ShouldSkipType() { return IsExcluded && !IsIncluded; }
private static bool TryWriteSelfType(TextWriter writer)
{
if (ShouldSkipType()) return false;
Serializer.WriteRawString(writer, JsConfig.TypeAttr);
writer.Write(JsWriter.MapKeySeperator);
Serializer.WriteRawString(writer, JsConfig.TypeWriter(typeof(T)));
return true;
}
private static bool TryWriteTypeInfo(TextWriter writer, object obj)
{
if (obj == null || ShouldSkipType()) return false;
Serializer.WriteRawString(writer, JsConfig.TypeAttr);
writer.Write(JsWriter.MapKeySeperator);
Serializer.WriteRawString(writer, JsConfig.TypeWriter(obj.GetType()));
return true;
}
public static WriteObjectDelegate Write
{
get { return CacheFn; }
}
private static WriteObjectDelegate GetWriteFn()
{
return WriteProperties;
}
static Func<T, bool> GetShouldSerializeMethod(MemberInfo member)
{
var method = member.DeclaringType.GetMethod("ShouldSerialize" + member.Name, BindingFlags.Instance | BindingFlags.Public,
null, Type.EmptyTypes, null);
return (method == null || method.ReturnType != typeof(bool)) ? null : (Func<T,bool>)Delegate.CreateDelegate(typeof(Func<T,bool>), method);
}
static Func<T,string, bool?> ShouldSerialize(Type type)
{
var method = type.GetMethod("ShouldSerialize", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(string) }, null);
return (method == null || method.ReturnType != typeof(bool?))
? null
: (Func<T, string, bool?>)Delegate.CreateDelegate(typeof(Func<T,string, bool?>), method);
}
private static bool Init()
{
if (!typeof(T).IsClass() && !typeof(T).IsInterface() && !JsConfig.TreatAsRefType(typeof(T))) return false;
var isDataContract = typeof(T).IsDto();
var propertyInfos = TypeConfig<T>.Properties;
var fieldInfos = JsConfig.IncludePublicFields || isDataContract ? TypeConfig<T>.Fields : new FieldInfo[0];
var propertyNamesLength = propertyInfos.Length;
var fieldNamesLength = fieldInfos.Length;
PropertyWriters = new TypePropertyWriter[propertyNamesLength + fieldNamesLength];
if (propertyNamesLength + fieldNamesLength == 0 && !JsState.IsWritingDynamic)
{
return typeof(T).IsDto();
}
var shouldSerializeByName = ShouldSerialize(typeof(T));
// NOTE: very limited support for DataContractSerialization (DCS)
// NOT supporting Serializable
// support for DCS is intended for (re)Name of properties and Ignore by NOT having a DataMember present
for (var i = 0; i < propertyNamesLength; i++)
{
var propertyInfo = propertyInfos[i];
string propertyName, propertyNameCLSFriendly, propertyNameLowercaseUnderscore, propertyReflectedName;
int propertyOrder = -1;
var propertyType = propertyInfo.PropertyType;
var defaultValue = propertyType.GetDefaultValue();
bool propertySuppressDefaultConfig = defaultValue != null && propertyType.IsValueType() && JsConfig.HasSerializeFn.Contains(propertyType);
bool propertySuppressDefaultAttribute = false;
var shouldSerialize = GetShouldSerializeMethod(propertyInfo);
if (isDataContract)
{
var dcsDataMember = propertyInfo.GetDataMember();
if (dcsDataMember == null) continue;
propertyName = dcsDataMember.Name ?? propertyInfo.Name;
propertyNameCLSFriendly = dcsDataMember.Name ?? propertyName.ToCamelCase();
propertyNameLowercaseUnderscore = dcsDataMember.Name ?? propertyName.ToLowercaseUnderscore();
propertyReflectedName = dcsDataMember.Name ?? propertyInfo.ReflectedType.Name;
// Fields tend to be at topp, push down properties to make it more like common.
propertyOrder = dcsDataMember.Order == DataMemberOrderNotSet ? 0 : dcsDataMember.Order;
propertySuppressDefaultAttribute = !dcsDataMember.EmitDefaultValue;
}
else
{
propertyName = propertyInfo.Name;
propertyNameCLSFriendly = propertyName.ToCamelCase();
propertyNameLowercaseUnderscore = propertyName.ToLowercaseUnderscore();
propertyReflectedName = propertyInfo.ReflectedType.Name;
}
PropertyWriters[i] = new TypePropertyWriter
(
propertyName,
propertyReflectedName,
propertyNameCLSFriendly,
propertyNameLowercaseUnderscore,
propertyOrder,
propertySuppressDefaultConfig,
propertySuppressDefaultAttribute,
propertyInfo.GetValueGetter<T>(),
Serializer.GetWriteFn(propertyType),
propertyType.GetDefaultValue(),
shouldSerialize,
shouldSerializeByName
);
}
for (var i = 0; i < fieldNamesLength; i++)
{
var fieldInfo = fieldInfos[i];
string propertyName, propertyNameCLSFriendly, propertyNameLowercaseUnderscore, propertyReflectedName;
int propertyOrder = -1;
var propertyType = fieldInfo.FieldType;
var defaultValue = propertyType.GetDefaultValue();
bool propertySuppressDefaultConfig = defaultValue != null && propertyType.IsValueType() && JsConfig.HasSerializeFn.Contains(propertyType);
bool propertySuppressDefaultAttribute = false;
var shouldSerialize = GetShouldSerializeMethod(fieldInfo);
if (isDataContract)
{
var dcsDataMember = fieldInfo.GetDataMember();
if (dcsDataMember == null) continue;
propertyName = dcsDataMember.Name ?? fieldInfo.Name;
propertyNameCLSFriendly = dcsDataMember.Name ?? propertyName.ToCamelCase();
propertyNameLowercaseUnderscore = dcsDataMember.Name ?? propertyName.ToLowercaseUnderscore();
propertyReflectedName = dcsDataMember.Name ?? fieldInfo.ReflectedType.Name;
propertyOrder = dcsDataMember.Order;
propertySuppressDefaultAttribute = !dcsDataMember.EmitDefaultValue;
}
else
{
propertyName = fieldInfo.Name;
propertyNameCLSFriendly = propertyName.ToCamelCase();
propertyNameLowercaseUnderscore = propertyName.ToLowercaseUnderscore();
propertyReflectedName = fieldInfo.ReflectedType.Name;
}
PropertyWriters[i + propertyNamesLength] = new TypePropertyWriter
(
propertyName,
propertyReflectedName,
propertyNameCLSFriendly,
propertyNameLowercaseUnderscore,
propertyOrder,
propertySuppressDefaultConfig,
propertySuppressDefaultAttribute,
fieldInfo.GetValueGetter<T>(),
Serializer.GetWriteFn(propertyType),
defaultValue,
shouldSerialize,
shouldSerializeByName
);
}
PropertyWriters = PropertyWriters.OrderBy(x => x.propertyOrder).ToArray();
return true;
}
internal struct TypePropertyWriter
{
internal string PropertyName
{
get
{
return (JsConfig<T>.EmitCamelCaseNames || JsConfig.EmitCamelCaseNames)
? propertyNameCLSFriendly
: (JsConfig<T>.EmitLowercaseUnderscoreNames || JsConfig.EmitLowercaseUnderscoreNames)
? propertyNameLowercaseUnderscore
: propertyName;
}
}
internal readonly string propertyName;
internal readonly int propertyOrder;
internal readonly bool propertySuppressDefaultConfig;
internal readonly bool propertySuppressDefaultAttribute;
internal readonly string propertyReflectedName;
internal readonly string propertyCombinedNameUpper;
internal readonly string propertyNameCLSFriendly;
internal readonly string propertyNameLowercaseUnderscore;
internal readonly Func<T, object> GetterFn;
internal readonly WriteObjectDelegate WriteFn;
internal readonly object DefaultValue;
internal readonly Func<T, bool> shouldSerialize;
internal readonly Func<T, string, bool?> shouldSerializeByName;
public TypePropertyWriter(string propertyName, string propertyReflectedName, string propertyNameCLSFriendly, string propertyNameLowercaseUnderscore, int propertyOrder, bool propertySuppressDefaultConfig,bool propertySuppressDefaultAttribute,
Func<T, object> getterFn, WriteObjectDelegate writeFn, object defaultValue, Func<T, bool> shouldSerialize, Func<T,string, bool?> shouldSerializeByName)
{
this.propertyName = propertyName;
this.propertyOrder = propertyOrder;
this.propertySuppressDefaultConfig = propertySuppressDefaultConfig;
this.propertySuppressDefaultAttribute = propertySuppressDefaultAttribute;
this.propertyReflectedName = propertyReflectedName;
this.propertyCombinedNameUpper = propertyReflectedName.ToUpper() + "." + propertyName.ToUpper();
this.propertyNameCLSFriendly = propertyNameCLSFriendly;
this.propertyNameLowercaseUnderscore = propertyNameLowercaseUnderscore;
this.GetterFn = getterFn;
this.WriteFn = writeFn;
this.DefaultValue = defaultValue;
this.shouldSerialize = shouldSerialize;
this.shouldSerializeByName = shouldSerializeByName;
}
}
public static void WriteObjectType(TextWriter writer, object value)
{
writer.Write(JsWriter.EmptyMap);
}
public static void WriteEmptyType(TextWriter writer, object value)
{
if (WriteTypeInfo != null || JsState.IsWritingDynamic)
{
writer.Write(JsWriter.MapStartChar);
if (!(JsConfig.PreferInterfaces && TryWriteSelfType(writer)))
{
TryWriteTypeInfo(writer, value);
}
writer.Write(JsWriter.MapEndChar);
return;
}
writer.Write(JsWriter.EmptyMap);
}
public static void WriteAbstractProperties(TextWriter writer, object value)
{
if (value == null)
{
writer.Write(JsWriter.EmptyMap);
return;
}
var valueType = value.GetType();
if (valueType.IsAbstract())
{
WriteProperties(writer, value);
return;
}
var writeFn = Serializer.GetWriteFn(valueType);
if (!JsConfig<T>.ExcludeTypeInfo) JsState.IsWritingDynamic = true;
writeFn(writer, value);
if (!JsConfig<T>.ExcludeTypeInfo) JsState.IsWritingDynamic = false;
}
public static void WriteProperties(TextWriter writer, object value)
{
if (typeof(TSerializer) == typeof(JsonTypeSerializer) && JsState.WritingKeyCount > 0)
writer.Write(JsWriter.QuoteChar);
writer.Write(JsWriter.MapStartChar);
var i = 0;
if (WriteTypeInfo != null || JsState.IsWritingDynamic)
{
if (JsConfig.PreferInterfaces && TryWriteSelfType(writer)) i++;
else if (TryWriteTypeInfo(writer, value)) i++;
JsState.IsWritingDynamic = false;
}
if (PropertyWriters != null)
{
var len = PropertyWriters.Length;
var exclude = JsConfig.ExcludePropertyReferences ?? new string[0];
ConvertToUpper(exclude);
var hasValueNotNull = (value != null);
for (int index = 0; index < len; index++)
{
var propertyWriter = PropertyWriters[index];
if (hasValueNotNull && propertyWriter.shouldSerialize != null && !propertyWriter.shouldSerialize((T)value)) continue;
bool dontSkipDefault=false;
if (hasValueNotNull && propertyWriter.shouldSerializeByName != null)
{
var shouldSerialize = propertyWriter.shouldSerializeByName((T) value, propertyWriter.PropertyName);
if (shouldSerialize.HasValue)
{
if (shouldSerialize.Value)
{
dontSkipDefault = true;
}
else
{
continue;
}
}
}
var propertyValue = hasValueNotNull
? propertyWriter.GetterFn((T)value)
: null;
if (!dontSkipDefault)
{
if (propertyWriter.propertySuppressDefaultAttribute && Equals(propertyWriter.DefaultValue, propertyValue))
{
continue;
}
if ((propertyValue == null
|| (propertyWriter.propertySuppressDefaultConfig && Equals(propertyWriter.DefaultValue, propertyValue)))
&& !Serializer.IncludeNullValues
)
{
continue;
}
}
if (exclude.Any() && exclude.Contains(propertyWriter.propertyCombinedNameUpper)) continue;
if (i++ > 0)
writer.Write(JsWriter.ItemSeperator);
Serializer.WritePropertyName(writer, propertyWriter.PropertyName);
writer.Write(JsWriter.MapKeySeperator);
if (typeof(TSerializer) == typeof(JsonTypeSerializer)) JsState.IsWritingValue = true;
try
{
if (propertyValue == null)
{
writer.Write(JsonUtils.Null);
}
else
{
propertyWriter.WriteFn(writer, propertyValue);
}
}
finally
{
if (typeof(TSerializer) == typeof(JsonTypeSerializer)) JsState.IsWritingValue = false;
}
}
}
writer.Write(JsWriter.MapEndChar);
if (typeof(TSerializer) == typeof(JsonTypeSerializer) && JsState.WritingKeyCount > 0)
writer.Write(JsWriter.QuoteChar);
}
private static readonly char[] ArrayBrackets = new[] { '[', ']' };
public static void WriteQueryString(TextWriter writer, object value)
{
try
{
JsState.QueryStringMode = true;
var i = 0;
foreach (var propertyWriter in PropertyWriters)
{
var propertyValue = propertyWriter.GetterFn((T)value);
if (propertyValue == null) continue;
if (i++ > 0)
writer.Write('&');
Serializer.WritePropertyName(writer, propertyWriter.PropertyName);
writer.Write('=');
var isEnumerable = propertyValue != null
&& !(propertyValue is string)
&& !(propertyValue.GetType().IsValueType())
&& propertyValue.GetType().HasInterface(typeof(IEnumerable));
if (!isEnumerable)
{
propertyWriter.WriteFn(writer, propertyValue);
}
else
{
//Trim brackets in top-level lists in QueryStrings, e.g: ?a=[1,2,3] => ?a=1,2,3
using (var ms = new MemoryStream())
using (var enumerableWriter = new StreamWriter(ms))
{
propertyWriter.WriteFn(enumerableWriter, propertyValue);
enumerableWriter.Flush();
var output = ms.ToArray().FromUtf8Bytes();
output = output.Trim(ArrayBrackets);
writer.Write(output);
}
}
}
}
finally
{
JsState.QueryStringMode = false;
}
}
private static void ConvertToUpper(string[] strArray)
{
for (var i = 0; i < strArray.Length; ++i)
{
if (strArray[i] != null)
strArray[i] = strArray[i].ToUpper();
}
}
}
}