forked from ipald/nativescript-socket.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.android.ts
75 lines (66 loc) · 1.71 KB
/
helpers.android.ts
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
'use strict';
const JSONObject = org.json.JSONObject;
const JSONArray = org.json.JSONArray;
const JSONException = org.json.JSONException;
export function serialize(data: any): any {
let node;
switch (typeof data) {
case 'string':
case 'boolean':
case 'number':
return data;
case 'object':
if (data instanceof Date) {
return data.toJSON();
}
if (!data) {
return null;
}
if (Array.isArray(data)) {
node = new JSONArray();
data.forEach(function(v) {
node.put(serialize(v));
});
return node;
}
node = new JSONObject();
Object.keys(data).forEach(function(key) {
let v = data[key];
node.put(key, serialize(v));
});
return node;
default:
return null;
}
}
export function deserialize(nativeData: any): any {
if (nativeData === null || typeof nativeData !== 'object') {
return nativeData;
}
switch (nativeData.getClass().getName()) {
case 'java.lang.String':
return String(nativeData);
case 'java.lang.Boolean':
return String(nativeData) === 'true';
case 'java.lang.Integer':
case 'java.lang.Long':
case 'java.lang.Double':
return Number(String(nativeData));
case 'org.json.JSONArray':
let array = [];
for (let i = 0, l = nativeData.length(); i < l; i++) {
array[i] = deserialize(nativeData.get(i));
}
return array;
case 'org.json.JSONObject':
let dict = {};
let iterator = nativeData.keys();
while (iterator.hasNext()) {
let key = iterator.next();
dict[key] = deserialize(nativeData.get(key));
}
return dict;
default:
return null;
}
}