Skip to content

Commit 885de65

Browse files
committed
Added deserialization helpers for List and Map
1 parent cba74b9 commit 885de65

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package org.javawebstack.graph.util;
2+
3+
import com.google.gson.*;
4+
5+
import java.lang.reflect.Type;
6+
import java.util.ArrayList;
7+
import java.util.List;
8+
9+
public abstract class GsonListDeserializer<T> implements JsonDeserializer<List<T>> {
10+
protected abstract Class<T> getType();
11+
public List<T> deserialize(JsonElement json, Type type, JsonDeserializationContext deserializationContext) throws JsonParseException {
12+
if(json == null || !json.isJsonArray())
13+
return null;
14+
JsonArray jsonArray = json.getAsJsonArray();
15+
List<T> list = new ArrayList<>();
16+
Class<?> t = getType();
17+
for(JsonElement e : jsonArray)
18+
list.add(deserializationContext.deserialize(e, t));
19+
return list;
20+
}
21+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package org.javawebstack.graph.util;
2+
3+
import com.google.gson.*;
4+
5+
import java.lang.reflect.Type;
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
9+
public abstract class GsonMapDeserializer<T> implements JsonDeserializer<Map<String,T>> {
10+
protected abstract Class<T> getType();
11+
public Map<String, T> deserialize(JsonElement json, Type type, JsonDeserializationContext deserializationContext) throws JsonParseException {
12+
if(json == null || !json.isJsonObject())
13+
return null;
14+
JsonObject jsonObject = json.getAsJsonObject();
15+
Map<String, T> map = new HashMap<>();
16+
Class<?> t = getType();
17+
for(String k : jsonObject.keySet())
18+
map.put(k, deserializationContext.deserialize(jsonObject.get(k), t));
19+
return map;
20+
}
21+
}

0 commit comments

Comments
 (0)