Skip to content

Instantly share code, notes, and snippets.

@Firsto
Created June 14, 2017 13:00
Show Gist options
  • Save Firsto/808430f5a2363f39ccfaf30c2f14f180 to your computer and use it in GitHub Desktop.
Save Firsto/808430f5a2363f39ccfaf30c2f14f180 to your computer and use it in GitHub Desktop.
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public abstract class TableDataDeserializer<T> implements JsonDeserializer<T> {
private final List<String> tableNameList = new ArrayList<>();
protected void addTableName(String... tableName) {
if (tableName != null && tableName.length > 0) {
Collections.addAll(tableNameList, tableName);
}
}
@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonArray jsonArray = json.getAsJsonArray();
if (jsonArray.size() == 0) {
return null;
}
T returnedData = getInstance();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement tableElement = jsonArray.get(i);
JsonObject tableJsonObject = tableElement.getAsJsonObject();
String tableName = tableJsonObject.get("TableName").getAsString();
if (tableNameList.contains(tableName)) {
onDetectTableName(tableName, tableJsonObject, returnedData, context);
}
}
return returnedData;
}
protected abstract void onDetectTableName(String tableName, JsonObject tableJsonObject, T returnedData, JsonDeserializationContext context);
public abstract T getInstance();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment