-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJsonDocument.cs
526 lines (476 loc) · 20.7 KB
/
JsonDocument.cs
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
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Aerospike.Database.LINQPadDriver.Extensions
{
/// <summary>
/// The structure used for Exporting records from a set.
/// </summary>
public struct JsonExportStructure
{
/// <summary>
/// The namespace associated with this record
/// </summary>
public string NameSpace;
/// <summary>
/// The Set associated with this record
/// </summary>
public string SetName;
/// <summary>
/// The record's Generation.
/// <see cref="Aerospike.Client.Record.generation"/>
/// </summary>
public int Generation;
/// <summary>
/// The record's Time-to-Live.
/// <see cref="Aerospike.Client.Record.TimeToLive"/>
/// <see cref="ARecord.AerospikeAPI.Expiration"/>
/// </summary>
public int? TimeToLive;
/// <summary>
/// The Record's Digest (Required)
/// </summary>
public byte[] Digest;
/// <summary>
/// The primary key of the record (optional)
/// </summary>
public object KeyValue;
/// <summary>
/// The associated record's bins (required)
/// </summary>
public IDictionary<string, object> Values;
}
public class JsonDocument : Newtonsoft.Json.Linq.JObject
{
public JsonDocument(IDictionary<object, object> dict)
: base(Newtonsoft.Json.Linq.JObject.FromObject(dict))
{
}
public JsonDocument(IDictionary<string, object> dict)
: base(Newtonsoft.Json.Linq.JObject.FromObject(dict))
{
}
public JsonDocument(Newtonsoft.Json.Linq.JObject jObject)
: base(jObject)
{
}
/// <summary>
/// Selects a <see cref="T:Newtonsoft.Json.Linq.JToken" /> using a JSONPath expression. Selects the token that matches the object path.
/// <seealso cref="Newtonsoft.Json.Linq.JToken.SelectTokens(string)"/>
/// </summary>
/// <param name="jsonPath">
/// A <see cref="T:System.String" /> that contains a JSONPath expression.
/// </param>
/// <returns>A <see cref="T:Newtonsoft.Json.Linq.JToken" />, or <c>null</c>.</returns>
/// <seealso cref="Newtonsoft.Json.Linq.JToken.SelectToken(string, Newtonsoft.Json.Linq.JsonSelectSettings?)"/>
/// <seealso cref="Newtonsoft.Json.Linq.JToken.SelectTokens(string)"/>
public Newtonsoft.Json.Linq.JToken JsonPath(string jsonPath)
{
return this.SelectToken(jsonPath);
}
/// <summary>
/// Selects a Newtonsoft.Json.Linq.JToken using a JSONPath expression. Selects the
/// token that matches the object path.
/// <seealso cref="Newtonsoft.Json.Linq.JToken.SelectTokens(string, bool)"/>
/// </summary>
/// <param name="jsonPath">A System.String that contains a JSONPath expression.</param>
/// <param name="errorWhenNoMatch">
/// A flag to indicate whether an error should be thrown if no tokens are found when
/// evaluating part of the expression.
/// </param>
/// <returns>
/// <see cref="Newtonsoft.Json.Linq.JToken"/>
/// </returns>
/// <seealso cref="Newtonsoft.Json.Linq.JToken.SelectToken(string, Newtonsoft.Json.Linq.JsonSelectSettings?)"/>
/// <seealso cref="Newtonsoft.Json.Linq.JToken.SelectTokens(string, bool)"/>
public Newtonsoft.Json.Linq.JToken JsonPath(string jsonPath, bool errorWhenNoMatch)
{
return this.SelectToken(jsonPath, errorWhenNoMatch);
}
public IDictionary<string, object> ToDictionary() => CDTConverter.ConvertToDictionary(this);
}
/// <summary>
/// Converts Json string into a List<object> or Directory<string,object>.
/// The Json string can consist of in-line Json typing.
/// Example:
/// <code>
/// "_id": {"$oid": "578f6fa2df35c7fbdbaed8c6"}
/// "bucket_start_date": {"$date": { "$numberLong": "1545886800000"}}
/// </code>
/// </summary>
public class CDTConverter : JsonConverter
{
private long _oid = 0;
readonly bool _emptyStrIsNull = true;
public CDTConverter(bool treatEmptyStrAsNull = true)
{
this._emptyStrIsNull = treatEmptyStrAsNull;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var t = JToken.FromObject(value, serializer);
t.WriteTo(writer);
}
private object ReadObject(string propertyName, JToken jToken, JsonSerializer serializer)
{
if (propertyName[0] == '$')
{
if (propertyName.ToLower() == "$type")
{
var json = jToken.ToString();
var jSerial = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
return JsonConvert.DeserializeObject<object>(json, jSerial);
}
return ReadJsonType(propertyName, jToken, null, serializer);
}
return jToken.Value<object>();
}
private object ReadObject(JObject jObject, Dictionary<string, object> existingValue, JsonSerializer serializer)
{
bool onlyJsonType = false;
if (jObject.First is JProperty jProp
&& jProp.Name.ToLower() == "$type")
{
var newobject = ReadObject(jProp.Name, jObject, serializer);
existingValue.Add(jProp.Name,
newobject);
return newobject;
}
foreach (var kvp in jObject)
{
if (kvp.Key[0] == '$')
{
existingValue.Add(kvp.Key,
ReadObject(kvp.Key, kvp.Value, serializer));
onlyJsonType = true;
}
else if (kvp.Value is JObject subObject)
{
var newObject = new Dictionary<string, object>();
existingValue.Add(kvp.Key,
this.ReadObject(subObject, newObject, serializer));
}
else if (kvp.Value is JArray jArray)
{
var newList = new List<object>();
this.ReadObject(jArray, newList, serializer);
existingValue.Add(kvp.Key, newList);
}
else if(this._emptyStrIsNull
&& kvp.Value.Type == JTokenType.String
&& kvp.Value is JValue jStrValue)
{
var strValue = jStrValue.Value<string>();
existingValue.Add(kvp.Key,
strValue == string.Empty
? null
: strValue);
}
else if (kvp.Value is JValue jValue)
{
existingValue.Add(kvp.Key, jValue.Value);
}
else
{
existingValue.Add(kvp.Key, kvp.Value.Value<object>());
}
}
return onlyJsonType && existingValue.Count == 1 ? existingValue.Values.First() : existingValue;
}
private void ReadObject(JArray jToken, List<object> existingValue, JsonSerializer serializer)
{
foreach (var element in jToken)
{
if (element is JObject subObject)
{
var newObject = new Dictionary<string, object>();
existingValue.Add(this.ReadObject(subObject, newObject, serializer));
}
else if (element is JArray jArray)
{
var newList = new List<object>();
this.ReadObject(jArray, newList, serializer);
existingValue.Add(newList);
}
else if(this._emptyStrIsNull
&& element.Type == JTokenType.String
&& element is JValue jStrValue)
{
var strValue = jStrValue.Value<string>();
existingValue.Add(strValue == string.Empty
? null
: strValue);
}
else if (element is JValue jValue)
{
existingValue.Add(jValue.Value);
}
else
{
existingValue.Add(element.Value<object>());
}
}
}
private void ReadObject(JProperty jToken, Dictionary<string, object> existingValue, JsonSerializer serializer)
{
foreach (var element in jToken.Value)
{
if (element is JObject subObject)
{
var newObject = new Dictionary<string, object>();
existingValue.Add(jToken.Name, this.ReadObject(subObject, newObject, serializer));
}
else if (element is JArray jArray)
{
var newList = new List<object>();
this.ReadObject(jArray, newList, serializer);
existingValue.Add(jToken.Name, newList);
}
else if(this._emptyStrIsNull
&& element.Type == JTokenType.String
&& element is JValue jStrValue)
{
var strValue = jStrValue.Value<string>();
existingValue.Add(jToken.Name,
strValue == string.Empty
? null
: strValue);
}
else if (element is JValue jValue)
{
existingValue.Add(jToken.Name, jValue.Value);
}
else
{
existingValue.Add(jToken.Name, element.Value<object>());
}
}
}
/// <summary>
/// Determines the in-line Json Type and converts the Json value to that C# type
/// <code>
/// "$date" or "$datetime",
/// This can include an optional sub Json Type.Example:
/// " bucket_start_date": {"$date": { "$numberLong": "1545886800000"}}
/// "$datetimeoffset",
/// This can include an optional sub Json Type. Example:
/// " bucket_start_date ": { "$datetimeoffset": { "$numberLong": "1545886800000" } },
/// "$timespan",
/// This can include an optional sub Json Type. Example:
/// " bucket_start_time ": { "$timespan": { "$numberLong": "1545886800000" } },
/// "$timestamp",
/// "$guid" or "$uuid",
/// "$oid" or "$id",
/// If the Json string value equals 40 in length it will be treated as a digest and converted into a byte array.
/// Example:
/// " _id": { "$oid":"0080a245fabe57999707dc41ced60edc4ac7ac40" } ==> "_id":[00 80 A2 45 FA BE 57 99 97 07 DC 41 CE D6 0E DC 4A C7 AC 40]
/// This type can also take an optional keyword as a value. They are:
/// $guid or $uuid -- If provided, a new guid/uuid is generate as a unique value used
/// $numeric -- a sequential number starting at 1 will be used
/// Example:
/// " _id": { "$oid": "$uuid" } ==> Generates a new uuid as the _id value
/// "$numberint64" or "$numberlong" or "$long",
/// "$numberint32", or "$numberint" or "$int",
/// "$numberdecimal" or "$decimal",
/// "$numberdouble" or "$double" or "$number" or "$numeric",
/// "$numberfloat" or "$single" or "$float",
/// "$numberint16" or "$numbershort" or "$short",
/// "$numberuint32" or "$numberuint" or "$uint",
/// "$numberuint64" or "$numberulong" or "$ulong",
/// "$numberuint16" or "$numberushort" or "$ushort",
/// "$bool" or "$boolean"
/// </code>
/// </summary>
/// <param name="propType"></param>
/// <param name="jToken"></param>
/// <param name="_"></param>
/// <param name="serializer"></param>
/// <returns></returns>
private object ReadJsonType(string propType, JToken jToken, object _, JsonSerializer serializer)
{
var tToken = jToken.Type;
object vToken;
if (jToken is JObject jObject)
{
var newObject = new Dictionary<string, object>();
vToken = this.ReadObject(jObject, newObject, serializer);
}
else if (jToken is JValue jValue)
{
vToken = jValue.Value;
}
else
vToken = jToken.Value<object>();
switch (propType.ToLower())
{
case "$string":
return vToken?.ToString() ?? string.Empty;
case "$date":
case "$datetime":
case "$isodate":
case "$isodatetime":
{
if (vToken is DateTime tDateTime)
return tDateTime;
if (vToken is long lDateTime)
return DateTimeOffset.FromUnixTimeMilliseconds(lDateTime).DateTime;
if (vToken is int iDateTime)
return DateTimeOffset.FromUnixTimeMilliseconds(iDateTime).DateTime;
if (tToken == JTokenType.Integer)
{
return DateTimeOffset.FromUnixTimeMilliseconds(Convert.ToInt64(vToken)).DateTime;
}
return Aerospike.Database.LINQPadDriver.Helpers.CastToNativeType(propType, typeof(DateTime), propType, vToken);
}
case "$datetimeoffset":
case "$isodatetimeoffset":
{
if (vToken is DateTimeOffset tDateTime)
return tDateTime;
if (vToken is long lDateTime)
return DateTimeOffset.FromUnixTimeMilliseconds(lDateTime);
if (vToken is int iDateTime)
return DateTimeOffset.FromUnixTimeMilliseconds(iDateTime).DateTime;
if (tToken == JTokenType.Integer)
{
return DateTimeOffset.FromUnixTimeMilliseconds(Convert.ToInt64(vToken));
}
return Aerospike.Database.LINQPadDriver.Helpers.CastToNativeType(propType, typeof(DateTimeOffset), propType, vToken);
}
case "$timespan":
case "$time":
return Aerospike.Database.LINQPadDriver.Helpers.CastToNativeType(propType, typeof(TimeSpan), propType, vToken);
case "$timestamp":
return vToken;
case "$guid":
case "$uuid":
{
if (vToken is Guid guid)
return guid;
if (vToken is string sGuid)
return Guid.Parse(sGuid);
return vToken;
}
case "$oid":
case "$id":
{
if (vToken is string oid)
{
if (oid.Length == 40)
return Aerospike.Database.LINQPadDriver.Helpers.StringToByteArray(oid);
switch (oid.ToLower())
{
case "$guid":
case "$uuid":
return Guid.NewGuid().ToString();
case "$number":
case "$numeric":
return System.Threading.Interlocked.Increment(ref this._oid);
default:
break;
}
}
return vToken;
}
case "$numberint64":
case "$numberlong":
case "$long":
return Convert.ToInt64(vToken);
case "$numberint32":
return Convert.ToInt32(vToken);
case "$numberint":
case "$int":
return Convert.ToInt32(vToken);
case "$numberdecimal":
case "$decimal":
return Convert.ToDecimal(vToken);
case "$numberdouble":
case "$double":
case "$number":
case "$numeric":
return Convert.ToDouble(vToken);
case "$numberfloat":
case "$float":
case "$single":
return Convert.ToSingle(vToken);
case "$numberint16":
case "$numbershort":
case "$short":
return Convert.ToInt16(vToken);
case "$numberuint32":
case "$numberuint":
case "$uint":
return Convert.ToUInt32(vToken);
case "$numberuint64":
case "$numberulong":
case "$ulong":
return Convert.ToUInt64(vToken);
case "$numberuint16":
case "$numberushort":
case "$ushort":
return Convert.ToUInt16(vToken);
case "$bool":
case "$boolean":
return Convert.ToBoolean(vToken);
default:
return vToken;
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jToken = JToken.ReadFrom(reader);
if (jToken is JArray jArray)
{
var arrayToken = new List<object>();
this.ReadObject(jArray, arrayToken, serializer);
return arrayToken;
}
else if (jToken is JObject jObject)
{
var objectToken = new Dictionary<string, object>();
this.ReadObject(jObject, objectToken, serializer);
if(objectToken.Count == 1 && objectToken.First().Key.ToLower() == "$type")
{
return Helpers.TransForm(objectToken.First().Value);
}
return objectToken;
}
else
throw new InvalidOperationException($"Must be either a JObect or JArray Json Token, not {reader.TokenType} ({reader.TokenType.GetType()})");
}
public override bool CanRead
{
get { return true; }
}
public override bool CanConvert(Type objectType)
{
return true;
}
static public IDictionary<string,object> ConvertToDictionary(JObject jObject)
{
var converter = new CDTConverter();
var newDict = new Dictionary<string,object>();
converter.ReadObject(jObject, newDict, null);
return newDict;
}
static public IDictionary<string, object> ConvertToDictionary(JProperty jProperty)
{
var converter = new CDTConverter();
var newDict = new Dictionary<string, object>();
converter.ReadObject(jProperty, newDict, null);
return newDict;
}
static public IList<object> ConvertToList(JArray jObject)
{
var converter = new CDTConverter();
var newList = new List<object>();
converter.ReadObject(jObject, newList, null);
return newList;
}
}
}