Skip to content

Commit 1f02b58

Browse files
committed
Added deserialization helpers for custom Enums
1 parent 885de65 commit 1f02b58

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package org.javawebstack.graph.util;
2+
3+
public interface GsonEnum {
4+
String gsonValue();
5+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package org.javawebstack.graph.util;
2+
3+
import com.google.gson.*;
4+
5+
import java.lang.reflect.Type;
6+
7+
public class GsonEnumAdapter implements JsonSerializer<GsonEnum>, JsonDeserializer<GsonEnum> {
8+
9+
public GsonEnum deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
10+
if(jsonElement == null || !jsonElement.isJsonPrimitive() || !jsonElement.getAsJsonPrimitive().isString())
11+
return null;
12+
String value = jsonElement.getAsJsonPrimitive().getAsString();
13+
if(!(type instanceof Class))
14+
return null;
15+
Class<GsonEnum> typeClass = (Class<GsonEnum>) type;
16+
if(!GsonEnum.class.isAssignableFrom(typeClass))
17+
return null;
18+
if(!typeClass.isEnum())
19+
return null;
20+
for(GsonEnum e : typeClass.getEnumConstants()){
21+
if(e.gsonValue().equals(value))
22+
return e;
23+
}
24+
return null;
25+
}
26+
27+
public JsonElement serialize(GsonEnum gsonEnum, Type type, JsonSerializationContext jsonSerializationContext) {
28+
return new JsonPrimitive(gsonEnum.gsonValue());
29+
}
30+
31+
}

0 commit comments

Comments
 (0)