-
Notifications
You must be signed in to change notification settings - Fork 7
/
core.clj
83 lines (71 loc) · 2.53 KB
/
core.clj
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
(ns pjson.core
(:import [pjson PJSON StringUtil JSONAssociative ToJSONString JSONGenerator]
(java.nio.charset Charset)
(java.util Map Collection)
(clojure.lang Seqable IPersistentMap))
(:gen-class))
(defonce ^Charset DEFAULT_CHARSET (StringUtil/DEFAULT_CHAR_SET))
(defprotocol JSONToString
"Convert an ordinary java/clojure object to a JSON compcatible String"
(write-str [obj]))
(defprotocol JSONParser
"Convert a json string to clojure objects lazily"
(read-str [obj] [obj ^Charset charset] [obj ^Charset charset ^Long from ^Long len]))
;compatibility functions for easy swap between other libraries
;note that only arity one support is added, use read-str for multi arity support
(defn asObj [obj] (read-str obj))
(defn parse-string [obj] (read-str obj))
(defn asString [obj] (write-str obj))
(defn generate-string [obj] (write-str obj))
(defn get-charset [n]
(Charset/forName (str n)))
(defn- bts->lazy-json
([^"[B" bts]
(bts->lazy-json DEFAULT_CHARSET bts))
([^Charset charset ^"[B" bts]
(PJSON/defaultLazyParse charset bts))
([^Charset charset ^"[B" bts ^Long from ^Long len]
(PJSON/defaultLazyParse charset bts (int from) (int len))))
(extend-protocol JSONParser
String
(read-str
([obj] (read-str (StringUtil/toCharArray ^String obj)))
([obj charset] (read-str (StringUtil/toCharArray ^String obj) ^Charset charset))
([obj charset from len] (read-str (StringUtil/toCharArray ^String obj) ^Charset charset ^Long from ^Long len))))
(extend-protocol JSONParser
(Class/forName "[C")
(read-str
([^"[C" obj]
(PJSON/defaultLazyParse DEFAULT_CHARSET ^"[C" obj))
([^"[C" obj charset]
(PJSON/defaultLazyParse ^Charset charset ^"[C" obj))
([^"[C" obj charset ^Long from ^Long len]
(PJSON/defaultLazyParse ^Charset charset ^"[C" obj (int from) (int len)))))
(extend-protocol JSONParser
(Class/forName "[B")
(read-str
([^"[B" obj]
(bts->lazy-json obj))
([^"[B" obj charset]
(bts->lazy-json charset obj))
([^"[B" obj charset from len]
(bts->lazy-json charset obj from len))))
(extend-protocol JSONToString
ToJSONString
(write-str [^ToJSONString this]
(.toString this))
IPersistentMap
(write-str [^IPersistentMap this]
(JSONGenerator/forObj this))
Map
(write-str [^Map this]
(JSONGenerator/forObj this))
Collection
(write-str [^Collection this]
(JSONGenerator/forObj this))
Seqable
(write-str [^Seqable this]
(JSONGenerator/forObj this))
Object
(write-str [^Object this]
(JSONGenerator/forObj this)))