Last active
October 4, 2015 11:11
-
-
Save iwarapter/8e1369ed0ed6d159a5b9 to your computer and use it in GitHub Desktop.
Gson-Fire TypeSelector Hierarchy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grab(group='io.gsonfire', module='gson-fire', version='1.3.1') | |
import com.google.gson.Gson | |
import com.google.gson.GsonBuilder | |
import com.google.gson.JsonElement | |
import io.gsonfire.GsonFireBuilder | |
import io.gsonfire.TypeSelector | |
GsonFireBuilder builder = new GsonFireBuilder() | |
.registerTypeSelector(Base.class, new TypeSelector<Base>() { | |
@Override | |
public Class<? extends Base> getClassForElement(JsonElement readElement) { | |
String type = readElement.getAsJsonObject().get("type").getAsString() | |
return Class.forName(type) | |
} | |
}) | |
Gson gson = builder.createGsonBuilder().setPrettyPrinting().create() | |
C c1 = new C() | |
c1.type = 'C' | |
C c2 = new C() | |
c2.type = 'C' | |
c1.myA = new B('B') | |
println gson.toJson(c1) | |
def obj = gson.fromJson(gson.toJson(c1), C.class) | |
println gson.toJson(c1) | |
abstract class Base { | |
String type | |
} | |
abstract class A extends Base { | |
String a = 'Abstract value' | |
} | |
class B extends A { | |
String b = 'Something B' | |
B(String type){ this.type = type } | |
} | |
class C extends Base { | |
A myA | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment