Skip to content

Instantly share code, notes, and snippets.

@gillesbraun
Created November 25, 2016 12:37
Show Gist options
  • Save gillesbraun/19610f530842c1dbf8e5e7097c39c567 to your computer and use it in GitHub Desktop.
Save gillesbraun/19610f530842c1dbf8e5e7097c39c567 to your computer and use it in GitHub Desktop.
Gson with abstract elements
package model.entities;
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 com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
/**
*
* @author gillesbraun
*/
public class EntityAdapter implements JsonSerializer<Entity>, JsonDeserializer<Entity> {
@Override
public JsonElement serialize(Entity t, Type type, JsonSerializationContext jsc) {
JsonObject result = new JsonObject();
result.add("type", new JsonPrimitive(t.getClass().getSimpleName()));
result.add("properties", jsc.serialize(t, t.getClass()));
return result;
}
@Override
public Entity deserialize(JsonElement je, Type typeOfT, JsonDeserializationContext jdc) throws JsonParseException {
JsonObject jsonObject = je.getAsJsonObject();
String type = jsonObject.get("type").getAsString();
JsonElement element = jsonObject.get("properties");
try {
return jdc.deserialize(element, Class.forName("model.entities."+type));
} catch (ClassNotFoundException ex) {
throw new JsonParseException("Unknown element type: "+type, ex);
}
}
}
public class Simulator {
private Cells readState, writeState;
public void saveToFile(String file) throws IOException {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Entity.class, new EntityAdapter());
Gson gson = gsonBuilder.create();
String json = gson.toJson(readState);
try (PrintWriter pw = new PrintWriter(new FileWriter(file))) {
pw.print(json);
}
}
public void loadFromFile(String file) throws FileNotFoundException, IOException {
String l = null, json = "";
BufferedReader br = new BufferedReader(new FileReader(file));
while((l = br.readLine()) != null) {
json += l;
}
br.close();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Entity.class, new EntityAdapter());
Gson gson = gsonBuilder.create();
readState = gson.fromJson(json, Cells.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment