-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonSectionAdapter.java
More file actions
33 lines (27 loc) · 1.18 KB
/
JsonSectionAdapter.java
File metadata and controls
33 lines (27 loc) · 1.18 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
package ru.javaops.webapp.util;
import com.google.gson.*;
import java.lang.reflect.Type;
public class JsonSectionAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> {
private static final String CLASSNAME = "CLASSNAME";
private static final String INSTANCE = "INSTANCE";
@Override
public T deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME);
String className = prim.getAsString();
try {
Class clazz = Class.forName(className);
return context.deserialize(jsonObject.get(INSTANCE), clazz);
} catch (ClassNotFoundException e) {
throw new JsonParseException(e.getMessage());
}
}
@Override
public JsonElement serialize(T section, Type type, JsonSerializationContext context) {
JsonObject retValue = new JsonObject();
retValue.addProperty(CLASSNAME, section.getClass().getName());
JsonElement elem = context.serialize(section);
retValue.add(INSTANCE, elem);
return retValue;
}
}