I have a concrete class called "Clerk" that implements an interface called "Worker". I want to deserialize my Clerk object and store it into a Worker object, just like we can normally do if I had this:
Worker clerkWorker = new Clerk("abc", "alice white");
Only instead I have the clerk json that I want to deserialize and store into clerkWorker:
{
"uid": "1a-2wq"
"name": "Maryanne Chen"
}
The interface:
public interface Worker {
int getUID();
String getName();
void work();
}
The class implementing it:
private class Clerk implements Worker {
int uid;
String name;
public Clerk(id, fullname) {
uid = id;
name = fullname;
}
public void work() {
System.out.println("Clerk is processing files");
}
}
Following the second solution described here: Using Gson with Interface Types I copied RuntimeTypeAdapterFactory locally to use it:
RuntimeTypeAdapterFactory typeFactory =
RuntimeTypeAdapterFactory.of(Worker.class, "type");
typeFactory.registerSubtype(Clerk.class);
Gson gson = new GsonBuilder().registerTypeAdapterFactory(typeFactory).create();
final Reader r = getReader(jsonFile);
return gson.fromJson(r, typeToken.getType());
I've verified my getReader function is working. I get an exception:
"cannot deserialize interface Worker because it does not define a field named type".