forked from JavaOPs/basejava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonSectionAdapter.java
More file actions
36 lines (31 loc) · 1.41 KB
/
JsonSectionAdapter.java
File metadata and controls
36 lines (31 loc) · 1.41 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
package com.urise.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 jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = jsonElement.getAsJsonObject();
//считываем свойство CLASSNAME - имя класса
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();
//добавляем свойство classname
retValue.addProperty(CLASSNAME, section.getClass().getName());
//сериализуем инстанс
JsonElement elem =context.serialize(section);
//добавляем инстанс
retValue.add(INSTANCE,elem);
return retValue;
}
}