-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiniJSON.cs
More file actions
320 lines (302 loc) · 9.58 KB
/
Copy pathMiniJSON.cs
File metadata and controls
320 lines (302 loc) · 9.58 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
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace LevelCollections;
/// <summary>
/// Minimal JSON serializer/deserializer compatible with Unity 2017.4 / .NET 3.5.
/// Adapted from the widely-used MiniJSON implementation for Unity.
/// Handles nested List<T> correctly — unlike JsonUtility in older Unity versions.
/// </summary>
public static class MiniJSON
{
public static string Serialize(object obj)
{
var sb = new StringBuilder();
SerializeValue(obj, sb);
return sb.ToString();
}
public static object Deserialize(string json)
{
if (string.IsNullOrEmpty(json))
return null;
int pos = 0;
SkipWhitespace(json, ref pos);
return ParseValue(json, ref pos);
}
// ── Serialize ─────────────────────────────────────────────────
private static void SerializeValue(object obj, StringBuilder sb)
{
if (obj == null)
{
sb.Append("null");
}
else if (obj is string)
{
SerializeString((string)obj, sb);
}
else if (obj is bool)
{
sb.Append((bool)obj ? "true" : "false");
}
else if (obj is int)
{
sb.Append((int)obj);
}
else if (obj is long)
{
sb.Append((long)obj);
}
else if (obj is float)
{
sb.Append(((float)obj).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
else if (obj is double)
{
sb.Append(((double)obj).ToString("R", System.Globalization.CultureInfo.InvariantCulture));
}
else if (obj is IDictionary)
{
SerializeDict((IDictionary)obj, sb);
}
else if (obj is IList)
{
SerializeList((IList)obj, sb);
}
else
{
// Treat as object: serialize public fields
SerializeObject(obj, sb);
}
}
private static void SerializeObject(object obj, StringBuilder sb)
{
sb.Append('{');
bool first = true;
var type = obj.GetType();
foreach (var field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (field.IsStatic) continue;
if (field.IsNotSerialized) continue;
// Skip properties with getters (Harmony/compiler-generated)
if (field.Name.StartsWith("<")) continue;
if (!first) sb.Append(',');
first = false;
SerializeString(field.Name, sb);
sb.Append(':');
SerializeValue(field.GetValue(obj), sb);
}
sb.Append('}');
}
private static void SerializeDict(IDictionary dict, StringBuilder sb)
{
sb.Append('{');
bool first = true;
foreach (DictionaryEntry kvp in dict)
{
if (!first) sb.Append(',');
first = false;
SerializeString(kvp.Key.ToString(), sb);
sb.Append(':');
SerializeValue(kvp.Value, sb);
}
sb.Append('}');
}
private static void SerializeList(IList list, StringBuilder sb)
{
sb.Append('[');
bool first = true;
foreach (var item in list)
{
if (!first) sb.Append(',');
first = false;
SerializeValue(item, sb);
}
sb.Append(']');
}
private static void SerializeString(string str, StringBuilder sb)
{
sb.Append('"');
foreach (char c in str)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32)
{
sb.Append("\\u" + ((int)c).ToString("X4"));
}
else
{
sb.Append(c);
}
break;
}
}
sb.Append('"');
}
// ── Deserialize ───────────────────────────────────────────────
private static object ParseValue(string json, ref int pos)
{
SkipWhitespace(json, ref pos);
if (pos >= json.Length) return null;
char c = json[pos];
switch (c)
{
case '"': return ParseString(json, ref pos);
case '{': return ParseDict(json, ref pos);
case '[': return ParseList(json, ref pos);
case 't': pos += 4; return true;
case 'f': pos += 5; return false;
case 'n': pos += 4; return null;
default: return ParseNumber(json, ref pos);
}
}
private static Dictionary<string, object> ParseDict(string json, ref int pos)
{
var dict = new Dictionary<string, object>();
pos++; // skip '{'
SkipWhitespace(json, ref pos);
if (json[pos] == '}')
{
pos++;
return dict;
}
while (true)
{
SkipWhitespace(json, ref pos);
string key = ParseString(json, ref pos);
SkipWhitespace(json, ref pos);
pos++; // skip ':'
object value = ParseValue(json, ref pos);
dict[key] = value;
SkipWhitespace(json, ref pos);
if (json[pos] == '}')
{
pos++;
return dict;
}
pos++; // skip ','
}
}
private static List<object> ParseList(string json, ref int pos)
{
var list = new List<object>();
pos++; // skip '['
SkipWhitespace(json, ref pos);
if (json[pos] == ']')
{
pos++;
return list;
}
while (true)
{
SkipWhitespace(json, ref pos);
object value = ParseValue(json, ref pos);
list.Add(value);
SkipWhitespace(json, ref pos);
if (json[pos] == ']')
{
pos++;
return list;
}
pos++; // skip ','
}
}
private static string ParseString(string json, ref int pos)
{
pos++; // skip opening '"'
var sb = new StringBuilder();
while (pos < json.Length)
{
char c = json[pos];
if (c == '"')
{
pos++;
return sb.ToString();
}
if (c == '\\')
{
pos++;
if (pos >= json.Length) break;
switch (json[pos])
{
case '"': sb.Append('"'); break;
case '\\': sb.Append('\\'); break;
case '/': sb.Append('/'); break;
case 'b': sb.Append('\b'); break;
case 'f': sb.Append('\f'); break;
case 'n': sb.Append('\n'); break;
case 'r': sb.Append('\r'); break;
case 't': sb.Append('\t'); break;
case 'u':
pos++;
if (pos + 4 > json.Length)
{
// Truncated unicode escape — append fallback
// and consume whatever remains so the outer
// pos++ doesn't overshoot.
sb.Append('?');
pos = json.Length - 1;
}
else
{
try
{
string hex = json.Substring(pos, 4);
sb.Append((char)Convert.ToInt32(hex, 16));
}
catch
{
// Invalid hex digits — fallback
sb.Append('?');
}
pos += 3;
}
break;
}
pos++;
}
else
{
sb.Append(c);
pos++;
}
}
return sb.ToString();
}
private static object ParseNumber(string json, ref int pos)
{
int start = pos;
while (pos < json.Length && (char.IsDigit(json[pos]) || json[pos] == '-' || json[pos] == '.' || json[pos] == 'e' || json[pos] == 'E' || json[pos] == '+'))
{
pos++;
}
string numStr = json.Substring(start, pos - start);
if (numStr.Contains("."))
{
if (double.TryParse(numStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double d))
return d;
}
else
{
if (long.TryParse(numStr, out long l))
return l;
}
return 0;
}
private static void SkipWhitespace(string json, ref int pos)
{
while (pos < json.Length && char.IsWhiteSpace(json[pos]))
{
pos++;
}
}
}