Last active
August 29, 2015 13:56
-
-
Save copolii/8892546 to your computer and use it in GitHub Desktop.
StackOverflow Question 21641022: How do I parse class hierarchies with gson?Link: http://stackoverflow.com/questions/21641022
This file contains hidden or 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
package com.copolii.example.so21641022.model.util; | |
import com.copolii.example.so21641022.model.a.TypeA_A; | |
import com.copolii.example.so21641022.model.a.TypeA_B; | |
import com.copolii.example.so21641022.model.b.TypeB_A; | |
import com.copolii.example.so21641022.model.b.TypeB_B; | |
import com.copolii.example.so21641022.model.base.AbstractSuperType; | |
import com.google.gson.Gson; | |
import com.google.gson.GsonBuilder; | |
import junit.framework.TestCase; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.junit.runners.JUnit4; | |
@RunWith(JUnit4.class) | |
public class CustomTypeAdapterFactoryTest extends TestCase { | |
private static Gson gson; | |
static { | |
gson = new GsonBuilder() | |
.registerTypeAdapterFactory(new CustomTypeAdapterFactory()) | |
.create(); | |
} | |
@Test | |
public void typeAA() { | |
final AbstractSuperType object = gson.fromJson("{\"ct\":1391877149,\"id\":\"abc123\", \"a\":{\"aa\":1 }}", AbstractSuperType.class); | |
final TypeA_A aa = (TypeA_A) object; | |
assertEquals(1391877149L, aa.getCreationTime()); | |
assertEquals("abc123", aa.getId()); | |
assertEquals(1, aa.getAA()); | |
} | |
@Test | |
public void typeAB() { | |
final AbstractSuperType object = gson.fromJson("{\"ct\":1391877149,\"id\":\"abc123\", \"a\":{\"ab\":234.2345, \"ab1\":\"Hello\"}}", AbstractSuperType.class); | |
final TypeA_B ab = (TypeA_B) object; | |
assertEquals(1391877149L, ab.getCreationTime()); | |
assertEquals("abc123", ab.getId()); | |
assertEquals(234.2345, ab.getAB()); | |
assertEquals("Hello", ab.getAB1()); | |
} | |
@Test | |
public void typeBA() { | |
final AbstractSuperType object = gson.fromJson("{\"ct\":1391877149,\"id\":\"abc123\", \"b\":{\"ba\":\"Jello\"}}", AbstractSuperType.class); | |
final TypeB_A ba = (TypeB_A) object; | |
assertEquals(1391877149L, ba.getCreationTime()); | |
assertEquals("abc123", ba.getId()); | |
assertEquals("Jello", ba.getBA()); | |
} | |
@Test | |
public void typeBB() { | |
final AbstractSuperType object = gson.fromJson("{\"ct\":1391877149,\"id\":\"abc123\", \"b\":{\"bb\":\"Jello\",\"bb1\":\"Mello\"}}", AbstractSuperType.class); | |
final TypeB_B bb = (TypeB_B) object; | |
assertEquals(1391877149L, bb.getCreationTime()); | |
assertEquals("abc123", bb.getId()); | |
assertEquals("Jello", bb.getBB()); | |
assertEquals("Mello", bb.getBB1()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment