forked from momodi/Json4Scala
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJson.scala
505 lines (467 loc) · 16.4 KB
/
Json.scala
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
/**
* Single class JSON parser
* Created by gaoyunxiang on 8/22/15.
* Modified by samikrc
* Last updated: 25-03-2022
*
* Source: https://github.com/samikrc/Json4Scala
* License: Apache 2.0.
*/
import java.time.format.DateTimeFormatter
import java.time.{Instant, ZoneId}
import scala.annotation.tailrec
import scala.collection.{immutable, mutable}
object Json
{
/**
* Incomplete JSON
* @param message
*/
case class IncompleteJSONException(val message: String) extends Exception(s"Parse error: the JSON string might be incomplete - $message")
/**
* Unrecognized characters
* @param char
* @param pos
*/
case class UnrecognizedCharException(val char: String, val pos: Int) extends Exception(s"Parse error: unrecognized character(s) '${char.substring(0, 6)}'... at position $pos - might be incomplete. Check for matching braces.")
/**
* Unknown Type
* @param message
*/
case class UnknownTypeException(val message: String) extends Exception(s"Parse error: the JSON string contains unknown Type- $message")
object Type extends Enumeration
{
val NULL, INT, DOUBLE, BOOLEAN, STRING, ARRAY, OBJECT = Value
}
/**
* Encapsulates a JSON structure from any of the supported data type.
* @param inputValue
*/
class Value(inputValue: Any)
{
def asInt: Int = value match
{
case v: Long if v.toInt == v => v.toInt
}
def isInt: Boolean = value.isInstanceOf[Long] || value.isInstanceOf[Int]
def asLong = value.asInstanceOf[Long]
def asDouble = value.asInstanceOf[Double]
def isDouble = value.isInstanceOf[Double]
def asBoolean = value.asInstanceOf[Boolean]
def isBoolean = value.isInstanceOf[Boolean]
def asString = value.asInstanceOf[String]
def isString = value.isInstanceOf[String]
def asArray = value.asInstanceOf[Array[Value]]
def isArray = value.isInstanceOf[Array[_]]
def asMap = value.asInstanceOf[Map[String, Value]]
def isMap = value.isInstanceOf[Map[_, _]]
def isNumeric = isInt || isDouble
def apply(i: Int): Value = value.asInstanceOf[Array[Value]](i)
def apply(key: String): Value = value.asInstanceOf[Map[String, Value]](key)
/**
* Method to write this object as JSON string.
* @return
*/
def write: String =
{
val buffer = new mutable.StringBuilder()
recWrite(buffer)
buffer.toString()
}
/**
* Method to write this object as JSON string, ending with newline.
* @return
*/
def writeln: String = s"${write}\n"
private val value: Any = inputValue match
{
case null => null
case v: Int => v.toLong
case _: Long => inputValue
case _: Double => inputValue
case _: Boolean => inputValue
case _: String => inputValue
// Adding Float: up-converting to double
case v: Float => v.toDouble
case v: Map[_, _] => v.map{ case (k, v) => (k.toString, Value(v)) }
// Adding mutable map classes
// Need separate entry for LinkedHashMap, otherwise we loose type.
case v: mutable.LinkedHashMap[_,_] => v.map{ case (k, v) => (k.toString, Value(v)) }
case v: mutable.Map[_, _] => v.map{ case (k, v) => (k.toString, Value(v)) }
// Adding mutable and immutable collection classes
case v: mutable.Iterable[_] => v.map(Value(_)).toArray
case v: immutable.Iterable[_] => v.map(Value(_)).toArray
//case v: Vector[_] => v.map(Value(_)).toArray
//case v: List[_] => v.map(Value(_)).toArray
case v: Array[_] => v.map(Value(_))
case v: Iterator[_] => v.map(Value(_)).toArray
case v: Instant => convertInstantToString(v)
case v: Value => v.value
case _ => throw new UnknownTypeException("$inputValue")
}
private def recWrite(buffer: mutable.StringBuilder): Unit =
{
value match
{
case null => buffer.append("null")
case v: Long => if(v.isNaN) buffer.append("null") else buffer.append(v)
case v: Boolean => buffer.append(v)
case v: Double => if(v.isNaN) buffer.append("null") else buffer.append(v)
case v: String =>
buffer.append('"')
v.foreach
{
each =>
{
if (each == '\\' || each == '"')
{
buffer.append('\\')
}
else if (each == '\b')
{
buffer.append("\\b")
}
else if (each == '\f')
{
buffer.append("\\f")
}
else if (each == '\n')
{
buffer.append("\\n")
}
else if (each == '\r')
{
buffer.append("\\r")
}
else if (each == '\t')
{
buffer.append("\\t")
}
else
{
buffer.append(each)
}
}
}
buffer.append('"')
case v: Array[_] =>
buffer.append('[')
for (i <- v.indices)
{
if (i != 0)
{
buffer.append(',')
}
v(i).asInstanceOf[Value].recWrite(buffer)
}
buffer.append(']')
case v: Map[_, _] =>
buffer.append('{')
var first = true
v.foreach
{
case one =>
if (!first)
{
buffer.append(',')
}
first = false
buffer.append('"')
buffer.append(one._1)
buffer.append('"')
buffer.append(':')
one._2.asInstanceOf[Value].recWrite(buffer)
}
buffer.append('}')
case v: mutable.LinkedHashMap[_, _] =>
buffer.append('{')
var first = true
v.foreach
{
case one =>
if (!first)
{
buffer.append(',')
}
first = false
buffer.append('"')
buffer.append(one._1)
buffer.append('"')
buffer.append(':')
one._2.asInstanceOf[Value].recWrite(buffer)
}
buffer.append('}')
case _ => throw new Exception("Unknown data type")
}
}
override def toString: String =
{
// Only convert to string if this is a single value
if(this.isInt) this.asInt.toString
else if(this.isDouble) this.asDouble.toString
else if(this.isString) this.asString
else if(this.isArray || this.isMap) super.toString
else this.asLong.toString
}
/**
* Method to check if a path in x.y.z format exists. Only works for
* successive maps with keys as "x", "y", "z" etc.
* @param path
* @return
*/
def has(path: String): Boolean =
{
// In this case, we need a try-catch block to ascertain path availability
try
{
traverseForFn[Boolean](path, (map: Map[String, Value], parts: List[String]) => map.contains(parts(0)))
}
catch
{
case ex: NoSuchElementException => false
case x => throw x
}
/*
@tailrec
def hasPath(map: Map[String, Value], parts: List[String]): Boolean =
{
if(parts.length == 1)
map.contains(parts(0))
else
{
if(map.contains(parts(0)))
hasPath(map(parts(0)).asMap, parts.splitAt(1)._2)
else
false
}
}
hasPath(this.asMap, path.split(".").toList)
*/
}
/**
* Method to get the Json.Value object given a path in x.y.z format. Only works for
* successive maps with keys as "x", "y", "z" etc.
* @param path
* @return
*/
def get(path: String): Json.Value =
{
traverseForFn[Json.Value](path, (map: Map[String, Value], parts: List[String]) => map(parts(0)))
/*
@tailrec
def getVal(map: Map[String, Value], parts: List[String]): Value =
{
if(parts.length == 1)
map(parts(0))
else
getVal(map(parts(0)).asMap, parts.splitAt(1)._2)
}
getVal(this.asMap, path.split('.').toList)
*/
}
/**
* A recursive traversal method for a given path and a given function. Meant to be
* used as a higher order function (HOF) for traversal-based utility, e.g., get/has.
* @param path
* @param f
* @tparam A
* @return
*/
private def traverseForFn[A](path: String, f: (Map[String, Value], List[String]) => A): A =
{
@tailrec
def traverse(map: Map[String, Value], parts: List[String]): A =
{
if(parts.length == 1)
f(map, parts)
else
traverse(map(parts(0)).asMap, parts.splitAt(1)._2)
/*
// Not sure how to do below elegantly!!
parts match
{
case h::t => getVal(map(h).asMap, t)
case _ => map(parts(0))
}
*/
}
traverse(this.asMap, path.split('.').toList)
}
/**
* convert Instant ToString ('yyyy-MM-dd HH:mm:ss' format)
*/
def convertInstantToString(instant: Instant): String =
{
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault()).format(instant)
}
}
object Value
{
def apply(in: Any): Value =
{
new Value(in)
}
}
def parse(p: String): Value =
{
val sta = mutable.ArrayBuffer[(Char, Any)]()
var i = 0
while (i < p.length)
{
if (p(i).isWhitespace || p(i) == '-' || p(i) == ':' || p(i) == ',')
{
}
else if (p(i) == '[')
{
sta.append(('[', null))
}
else if (p(i) == '{')
{
sta.append(('{', null))
}
else if (p(i) == ']')
{
val vec = mutable.ArrayStack[Value]()
while (sta.nonEmpty && sta.last._1 != '[')
{
vec.push(Value(sta.last._2))
sta.trimEnd(1)
}
if (sta.isEmpty || sta.last._1 != '[')
{
throw new IncompleteJSONException("[] does not match")
}
sta.trimEnd(1)
sta.append(('a', vec.iterator))
}
else if (p(i) == '}')
{
val now = mutable.HashMap[String, Value]()
while (sta.length >= 2 && sta.last._1 != '{')
{
val new_value: Value = Value(sta.last._2)
sta.trimEnd(1)
val new_key = sta.last._2.asInstanceOf[String]
sta.trimEnd(1)
now.update(new_key, new_value)
}
if (sta.isEmpty || sta.last._1 != '{')
{
throw new IncompleteJSONException("{} does not match")
}
sta.trimEnd(1)
sta.append(('o', now.toMap))
}
else if (p(i) == '"')
{
var j = i + 1
val S = new mutable.StringBuilder()
while (j < p.length && p(j) != '"')
{
if (p(j) == '\\')
{
if (p(j + 1) == 'b')
{
S.append('\b')
}
else if (p(j + 1) == 'f')
{
S.append('\f')
}
else if (p(j + 1) == 'n')
{
S.append('\n')
}
else if (p(j + 1) == 'r')
{
S.append('\r')
}
else if (p(j + 1) == 't')
{
S.append('\t')
}
else
{
S.append(p(j + 1))
}
j += 2
}
else
{
S.append(p(j))
j += 1
}
}
sta.append(('v', S.toString()))
i = j
}
else if (p(i).isDigit)
{
val is_double =
{
var j = i + 1
while (j < p.length && p(j).isDigit)
{
j += 1
}
j < p.length && (p(j) == '.' || p(j) == 'e' || p(j) == 'E')
}
val minus_flag = if (i > 0 && p(i - 1) == '-')
{
-1
}
else
{
1
}
var j = i
while (j < p.length && p(j) != ',' && p(j) != ']' && p(j) != '}')
{
j += 1
}
if (is_double)
{
val v = p.substring(i, j).replaceAll("[^a-zA-Z0-9.]+","").toDouble * minus_flag
sta.append(('d', v))
}
else
{
val v = p.substring(i, j).replaceAll("[^a-zA-Z0-9.]+","").toLong * minus_flag
sta.append(('i', v))
}
i = j - 1
}
else if (p.substring(i, i + 4) == "null")
{
sta.append(('n', null))
i += 3
}
else if (p.substring(i, i + 4) == "true")
{
sta.append(('b', true))
i += 3
}
else if (p.substring(i, i + 5) == "false")
{
sta.append(('b', false))
i += 4
}
else if (p.substring(i, i + 3) == "NaN")
{
sta.append(('d', Double.NaN))
i += 2
}
else
{
throw new UnrecognizedCharException(p.substring(i), i)
}
i += 1
}
if (sta.length != 1)
{
throw new IncompleteJSONException("Unknown parsing error")
}
Value(sta.head._2)
}
}