-
Notifications
You must be signed in to change notification settings - Fork 2
/
json-serializer.dylan
84 lines (67 loc) · 2.54 KB
/
json-serializer.dylan
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
module: json-serialization
synopsis: Support for serializing to JSON.
author: Bruce Mitchener
copyright: 2012, Data Fueled, LLC.
define class <json-serializer> (<serializer>)
end;
define method write-end-array (serializer :: <json-serializer>)
write(serializer.stream, "]");
end;
define method write-end-object (serializer :: <json-serializer>)
write(serializer.stream, "}");
end;
define method write-field-name (serializer :: <json-serializer>, field-name :: <field-name>)
write-object(serializer, field-name);
end;
define method write-separator-array (serializer :: <json-serializer>)
write(serializer.stream, ",");
end method write-separator-array;
define method write-separator-field-name (serializer :: <json-serializer>)
write(serializer.stream, ":");
end method write-separator-field-name;
define method write-separator-object (serializer :: <json-serializer>)
write(serializer.stream, ",");
end method write-separator-object;
define method write-start-array (serializer :: <json-serializer>)
write(serializer.stream, "[");
end;
define method write-start-object (serializer :: <json-serializer>)
write(serializer.stream, "{");
end;
define method write-object (serializer :: <json-serializer>, object :: <integer>)
format(serializer.stream, "%d", object);
end;
define method write-object (serializer :: <json-serializer>, object :: <float>)
write(serializer.stream, float-to-string(object));
end;
define method write-object (serializer :: <json-serializer>, object :: <symbol>)
write-object(serializer, as(<string>, object));
end;
define function escape-characters (string :: <byte-string>) => (string :: <byte-string>)
let output = make(limited(<stretchy-vector>, of: <byte-character>, size: string.size * 2));
for (char :: <byte-character> in string)
select (char)
'\\', '"', '\b', '\f', '\n', '\r', '\t' =>
add!(output, '\\');
add!(output, char);
otherwise =>
add!(output, char);
end;
end;
as(<byte-string>, output)
end;
define method write-object (serializer :: <json-serializer>, object :: <byte-string>)
let stream = serializer.stream;
write(stream, "\"");
write(stream, escape-characters(object));
write(stream, "\"");
end;
define method write-object (serializer :: <json-serializer>, object :: singleton(#f))
write(serializer.stream, "false");
end;
define method write-object (serializer :: <json-serializer>, object :: singleton(#t))
write(serializer.stream, "true");
end;
define function write-object-to-json-string (object)
write-object-to-string(<json-serializer>, object);
end;