-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathJSONHelper.cs
More file actions
487 lines (457 loc) · 13.5 KB
/
JSONHelper.cs
File metadata and controls
487 lines (457 loc) · 13.5 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
#if NETCORE
using GeneXus.Application;
#else
using Jayrock.Json;
#endif
using System.Runtime.Serialization;
using GeneXus.Configuration;
#if NETCORE
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Encodings.Web;
using System.Globalization;
#endif
namespace GeneXus.Utils
{
#if NETCORE
public class GxJsonConverter : JsonConverter<object>
{
public override bool CanConvert(Type typeToConvert)
{
return typeof(object) == typeToConvert;
}
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.True:
return true;
case JsonTokenType.False:
return false;
case JsonTokenType.StartArray:
return JsonSerializer.Deserialize<JArray>(ref reader, options);
case JsonTokenType.StartObject:
return JsonSerializer.Deserialize<JObject>(ref reader, options);
case JsonTokenType.Number:
if (reader.TryGetInt32(out int l))
return l;
else
if (reader.TryGetDecimal(out decimal d))
return d;
else
return reader.GetDouble();
case JsonTokenType.String:
return reader.GetString();
default:
using (JsonDocument document = JsonDocument.ParseValue(ref reader))
{
return document.RootElement.Clone();
}
}
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
internal class CustomGeospatialConverter : JsonConverter<Geospatial>
{
public override Geospatial Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
return null;
}
string jsonString = JsonDocument.ParseValue(ref reader).RootElement.GetRawText();
Geospatial geospatial = new Geospatial();
geospatial.FromString(jsonString);
return geospatial;
}
public override void Write(Utf8JsonWriter writer, Geospatial value, JsonSerializerOptions options)
{
string stringValue = value?.ToString();
JsonSerializer.Serialize(writer, stringValue, options);
}
}
internal class CustomDateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException("Deserialization is not supported.");
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(Convert.ToString(value, CultureInfo.InvariantCulture)); //"dd/MM/yyyy HH:mm:ss"
}
}
internal class TextJsonSerializer : GXJsonSerializer
{
internal override bool IsJsonNull(object jobject)
{
return jobject == null;
}
static JsonSerializerOptions DeserializationOptions = new JsonSerializerOptions() { Converters = { new GxJsonConverter() }, AllowTrailingCommas=true };
internal override T ReadJSON<T>(string json)
{
return JsonSerializer.Deserialize<T>(json, DeserializationOptions);
}
internal override string WriteJSON<T>(T kbObject)
{
if (kbObject != null)
{
return kbObject.ToString();
}
return null;
}
static JsonSerializerOptions JayrockCompatibleOptions = new JsonSerializerOptions() {
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
Converters = { new CustomDateTimeConverter() },
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals };
internal static string SerializeToJayrockCompatibleJson<T>(T value) where T : IJayrockCompatible
{
return JsonSerializer.Serialize(value, JayrockCompatibleOptions);
}
internal override string WriteNullableJSON(Dictionary<string, object> kbObject)
{
return JsonSerializer.Serialize(kbObject, new System.Text.Json.JsonSerializerOptions()
{
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
});
}
internal override string DefaultSerialize<T>(T value)
{
if (value != null)
{
return JsonSerializer.Serialize(value);
}
return null;
}
internal override bool IsJsonString(string jobject)
{
try
{
var jsonElement = JsonDocument.Parse(jobject).RootElement;
return jsonElement.ValueKind == JsonValueKind.Object || jsonElement.ValueKind == JsonValueKind.Array;
}
catch
{
return false;
}
}
}
#else
internal class JayRockJsonSerializer : GXJsonSerializer
{
internal override bool IsJsonNull(object jobject)
{
return jobject == Jayrock.Json.JNull.Value;
}
internal override bool IsJsonString(string jobject)
{
try
{
ReadJSON<JObject>(jobject);
return true;
}
catch
{
return false;
}
}
internal override T ReadJSON<T>(string json)
{
Jayrock.Json.JsonTextReader reader = new JsonTextReader(new StringReader(json));
return (T)reader.DeserializeNext();
}
internal override string WriteJSON<T>(T kbObject)
{
if (kbObject != null)
{
return kbObject.ToString();
}
return null;
}
internal override string WriteNullableJSON(Dictionary<string, object> kbObject)
{
JObject jsonObject = new JObject();
foreach (var kvp in kbObject)
{
jsonObject[kvp.Key] = kvp.Value;
}
return jsonObject.ToString();
}
}
#endif
internal enum GXJsonSerializerType
{
Utf8,
Jayrock,
TextJson
}
internal abstract class GXJsonSerializer
{
private static GXJsonSerializer s_instance = null;
private static object syncRoot = new object();
internal static GXJsonSerializer Instance
{
get
{
if (s_instance == null)
{
lock (syncRoot)
{
if (s_instance == null)
{
#if NETCORE
s_instance = new TextJsonSerializer();
#else
s_instance = new JayRockJsonSerializer();
#endif
}
}
}
return s_instance;
}
}
internal abstract bool IsJsonNull(object jobject);
internal abstract bool IsJsonString(string jobject);
internal abstract T ReadJSON<T>(string json) where T : class;
internal abstract string WriteJSON<T>(T kbObject) where T : class;
internal abstract string WriteNullableJSON(Dictionary<string, object> kbObject);
#if NETCORE
internal abstract string DefaultSerialize<T>(T value) where T : class;
#endif
}
public class JSONHelper
{
static readonly IGXLogger log = GXLoggerFactory.GetLogger<JSONHelper>();
static string WFCDateTimeFormat = Preferences.WFCDateTimeMillis ? DateTimeUtil.JsonDateFormatMillis : DateTimeUtil.JsonDateFormat;
public static bool IsJsonNull(object jobject)
{
return GXJsonSerializer.Instance.IsJsonNull(jobject);
}
public static bool IsJsonString(string jobject)
{
return GXJsonSerializer.Instance.IsJsonString(jobject);
}
public static T ReadJSON<T>(string json, GXBaseCollection<SdtMessages_Message> Messages = null) where T : class
{
try
{
if (!string.IsNullOrWhiteSpace(json))
{
return GXJsonSerializer.Instance.ReadJSON<T>(json);
}
else
{
GXUtil.ErrorToMessages("FromJson Error", "Empty json", Messages);
return default(T);
}
}
catch (Exception ex)
{
GXUtil.ErrorToMessages("FromJson Error", ex, Messages, false);
GXLogging.Error(log, "FromJsonError ", ex);
return default(T);
}
}
public static T ReadJavascriptJSON<T>(string json, GXBaseCollection<SdtMessages_Message> Messages = null) where T : class
{
try
{
if (!string.IsNullOrWhiteSpace(json))
{
return GXJsonSerializer.Instance.ReadJSON<T>(json);
}
else
{
GXUtil.ErrorToMessages("FromJson Error", "Empty json", Messages);
return default(T);
}
}
catch (Exception ex)
{
GXUtil.ErrorToMessages("FromJson Error", ex, Messages, false);
GXLogging.Error(log, "FromJsonError ", ex);
return default(T);
}
}
public static string WriteJSON<T>(T kbObject) where T:class
{
try
{
if (kbObject!=null)
{
return GXJsonSerializer.Instance.WriteJSON<T>(kbObject);
}
return null;
}
catch (Exception ex)
{
GXLogging.Error(log, "Serialize error ", ex);
}
return null;
}
internal static string WriteNullableJSON(Dictionary<string, object> kbObject)
{
try
{
if (kbObject != null)
{
return GXJsonSerializer.Instance.WriteNullableJSON(kbObject);
}
return null;
}
catch (Exception ex)
{
GXLogging.Error(log, "Serialize error ", ex);
}
return null;
}
public static string Serialize<T>(T kbObject) where T : class
{
return Serialize<T>(kbObject, Encoding.UTF8);
}
#if NETCORE
public static string DefaultSerialize<T>(T value) where T : class
{
try
{
return GXJsonSerializer.Instance.DefaultSerialize<T>(value);
}
catch (Exception ex)
{
GXLogging.Error(log, "DefaultSerialize error ", ex);
return null;
}
}
#endif
public static string Serialize<T>(T kbObject, Encoding encoding) where T : class
{
return Serialize<T>(kbObject, encoding, null);
}
public static string Serialize<T>(T kbObject, Encoding encoding, IEnumerable<Type> knownTypes) where T : class
{
try
{
DataContractJsonSerializerSettings settings = SerializationSettings(knownTypes);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings);
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, kbObject);
return encoding.GetString(stream.ToArray());
}
}
catch (Exception ex)
{
GXLogging.Error(log, "Serialize error ", ex);
}
return null;
}
internal static string Serialize<T>(T kbObject, DataContractJsonSerializerSettings settings) where T : class
{
try
{
Encoding encoding = Encoding.UTF8;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings);
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, kbObject);
return encoding.GetString(stream.ToArray());
}
}
catch (Exception ex)
{
GXLogging.Error(log, "Serialize error ", ex);
}
return null;
}
internal static string WCFSerialize<T>(T kbObject, Encoding encoding, IEnumerable<Type> knownTypes, bool useSimpleDictionaryFormat) where T : class
{
try
{
if (kbObject == JNull.Value || kbObject == null)
return "null";
var settings = WCFSerializationSettings(knownTypes, useSimpleDictionaryFormat);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings);
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, kbObject);
return encoding.GetString(stream.ToArray());
}
}
catch (Exception ex)
{
GXLogging.Error(log, "Serialize error ", ex);
}
return null;
}
internal static void WCFSerialize<T>(T kbObject, Encoding encoding, IEnumerable<Type> knownTypes, Stream stream) where T : class
{
try
{
var settings = WCFSerializationSettings(knownTypes);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings);
serializer.WriteObject(stream, kbObject);
}
catch (Exception ex)
{
GXLogging.Error(log, "Serialize error ", ex);
}
}
static DataContractJsonSerializerSettings SerializationSettings(IEnumerable<Type> knownTypes)
{
return new DataContractJsonSerializerSettings() { DateTimeFormat = new DateTimeFormat(DateTimeUtil.JsonDateFormatMillis), KnownTypes=knownTypes };
}
static DataContractJsonSerializerSettings WCFSerializationSettings(IEnumerable<Type> knownTypes, bool useSimpleDictionaryFormat=false) {
return new DataContractJsonSerializerSettings() { DateTimeFormat = new DateTimeFormat(WFCDateTimeFormat), EmitTypeInformation = EmitTypeInformation.Never, UseSimpleDictionaryFormat= useSimpleDictionaryFormat, KnownTypes=knownTypes };
}
public static T Deserialize<T>(string kbObject, Encoding encoding, IEnumerable<Type> knownTypes) where T : class, new()
{
return Deserialize<T>(kbObject, encoding, knownTypes, new T());
}
public static T Deserialize<T>(string kbObject, Encoding encoding, IEnumerable<Type> knownTypes, T defaultValue) where T : class
{
var settings = SerializationSettings(knownTypes);
return Deserialize<T>(kbObject, encoding, knownTypes, defaultValue, settings);
}
internal static T Deserialize<T>(string kbObject, Encoding encoding, IEnumerable<Type> knownTypes, T defaultValue, DataContractJsonSerializerSettings settings) where T : class
{
if (!string.IsNullOrWhiteSpace(kbObject))
{
try
{
using (MemoryStream stream = new MemoryStream(encoding.GetBytes(kbObject)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T), settings);
#pragma warning disable SCS0028 // Unsafe deserialization possible from {1} argument passed to '{0}'
return (T)serializer.ReadObject(stream);
#pragma warning restore SCS0028 // Unsafe deserialization possible from {1} argument passed to '{0}'
}
}
catch (Exception ex)
{
GXLogging.Error(log, "Deserialize error ", ex);
}
}
return defaultValue;
}
public static T Deserialize<T>(string kbObject, Encoding encoding) where T : class, new()
{
return Deserialize<T>(kbObject, encoding, null, new T());
}
public static T Deserialize<T>(string kbObject) where T : class, new()
{
return Deserialize<T>(kbObject, Encoding.Unicode);
}
public static T DeserializeNullDefaultValue<T>(string kbObject) where T : class
{
return Deserialize<T>(kbObject, Encoding.Unicode, null, null);
}
}
}