Created
September 21, 2016 18:07
-
-
Save patrickhammond/4e842a35cd5b5eebd1b3c80aa25e2e4d to your computer and use it in GitHub Desktop.
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
import com.google.gson.Gson; | |
import com.google.gson.annotations.SerializedName; | |
import org.junit.Before; | |
import org.junit.Test; | |
import static org.junit.Assert.assertEquals; | |
public class SampleJsonTest { | |
private static final String SAMPLE_JSON = "{ \"first_name\": \"Atomic\", \"last_name\": \"Robot\" }"; | |
private Gson gson; | |
@Before | |
public void setup() { | |
gson = new Gson(); | |
} | |
@Test | |
public void testParsingJsonAsMutablePerson() { | |
MutablePerson person = gson.fromJson(SAMPLE_JSON, MutablePerson.class); | |
assertEquals("Atomic", person.firstName); | |
assertEquals("Robot", person.lastName); | |
} | |
@Test | |
public void testParsingJsonAsImmutablePerson() { | |
// Works due to the magic of the ReflectiveTypeAdapterFactory | |
ImmutablePerson person = gson.fromJson(SAMPLE_JSON, ImmutablePerson.class); | |
assertEquals("Atomic", person.firstName); | |
assertEquals("Robot", person.lastName); | |
} | |
static class MutablePerson { | |
@SerializedName("first_name") String firstName; | |
@SerializedName("last_name") String lastName; | |
} | |
static class ImmutablePerson { | |
final @SerializedName("first_name") String firstName; | |
final @SerializedName("last_name") String lastName; | |
// Not called by GSON... | |
public ImmutablePerson(String firstName, String lastName) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment