-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathJSONObjectHelper.cpp
More file actions
69 lines (57 loc) · 1.94 KB
/
Copy pathJSONObjectHelper.cpp
File metadata and controls
69 lines (57 loc) · 1.94 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
#include "NativeScriptException.h"
#include "JSONObjectHelper.h"
#include "ArgConverter.h"
#include <sstream>
#include <string>
#include <cassert>
using namespace tns;
void JSONObjectHelper::RegisterFromFunction(napi_env env, napi_value value) {
napi_valuetype type;
napi_typeof(env, value, &type);
if (type != napi_function && type != napi_object) {
return;
}
bool hasProperty;
napi_has_named_property(env, value, "from", &hasProperty);
if (hasProperty) {
return;
}
napi_value from = CreateFromFunction(env);
napi_set_named_property(env, value, "from", from);
}
napi_value JSONObjectHelper::CreateFromFunction(napi_env env) {
static const char* source = R"((() => function from(data) {
if (!data) throw new Error("Expected one parameter");
let store;
switch (typeof data) {
case "string":
case "boolean":
case "number": {
return data;
}
case "object": {
if (!data) {
return null;
}
if (data instanceof Date) {
return data.toJSON();
}
if (Array.isArray(data)) {
store = new org.json.JSONArray();
data.forEach((item) => store.put(from(item)));
return store;
}
store = new org.json.JSONObject();
Object.keys(data).forEach((key) => store.put(key, from(data[key])));
return store;
}
default:
return null;
}
})();)";
napi_value script;
napi_create_string_utf8(env, source, NAPI_AUTO_LENGTH, &script);
napi_value result;
js_execute_script(env, script, "<from_function>", &result);
return result;
}