-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONSerializableFactory.java
More file actions
32 lines (25 loc) · 1 KB
/
JSONSerializableFactory.java
File metadata and controls
32 lines (25 loc) · 1 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
package jsonlib;
import jsonlib.types.JSONDict;
import java.util.HashMap;
import java.util.Map;
public class JSONSerializableFactory {
private static final Map<String, Class<? extends JSONSerializable>> typeRegistry = new HashMap<>();
public static void registerType(String type, Class<? extends JSONSerializable> clazz) {
typeRegistry.put(type, clazz);
}
public static JSONSerializable deserialize(JSONDict json) {
if (json == null) {
throw new IllegalArgumentException("Invalid JSON");
}
String type = json.getString("class");
Class<? extends JSONSerializable> clazz = typeRegistry.get(type);
if (clazz == null)
throw new IllegalArgumentException("Unknown type: " + type);
try {
java.lang.reflect.Method deserializeMethod = clazz.getMethod("deserialize", JSONDict.class);
return (JSONSerializable) deserializeMethod.invoke(null, json);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to deserialize: " + type, e);
}
}
}