Skip to content

Instantly share code, notes, and snippets.

@patrickhammond
Created September 21, 2016 18:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickhammond/4e842a35cd5b5eebd1b3c80aa25e2e4d to your computer and use it in GitHub Desktop.
Save patrickhammond/4e842a35cd5b5eebd1b3c80aa25e2e4d to your computer and use it in GitHub Desktop.
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