|
| 1 | +package org.baeldung.gson.serialization; |
| 2 | + |
| 3 | +import java.text.ParseException; |
| 4 | +import java.text.SimpleDateFormat; |
| 5 | +import java.util.Arrays; |
| 6 | + |
| 7 | +import org.baeldung.gson.entities.ActorGson; |
| 8 | +import org.baeldung.gson.entities.Movie; |
| 9 | +import org.baeldung.gson.entities.MovieWithNullValue; |
| 10 | +import org.baeldung.gson.serialization.ActorGsonDeserializer; |
| 11 | +import org.baeldung.gson.serialization.ActorGsonSerializer; |
| 12 | +import org.junit.Assert; |
| 13 | +import org.junit.Test; |
| 14 | + |
| 15 | +import com.google.gson.Gson; |
| 16 | +import com.google.gson.GsonBuilder; |
| 17 | +import com.google.gson.JsonParser; |
| 18 | + |
| 19 | +public class GsonSerializeTest { |
| 20 | + |
| 21 | + @Test |
| 22 | + public void whenSimpleSerialize_thenCorrect() throws ParseException { |
| 23 | + |
| 24 | + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); |
| 25 | + |
| 26 | + ActorGson rudyYoungblood = new ActorGson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); |
| 27 | + Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); |
| 28 | + |
| 29 | + String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Sep 21, 1982 12:00:00 AM\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; |
| 30 | + Assert.assertEquals(new Gson().toJson(movie), expectedOutput); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void whenCustomSerialize_thenCorrect() throws ParseException { |
| 35 | + Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().serializeNulls().disableHtmlEscaping().registerTypeAdapter(ActorGson.class, new ActorGsonSerializer()).create(); |
| 36 | + |
| 37 | + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); |
| 38 | + |
| 39 | + ActorGson rudyYoungblood = new ActorGson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); |
| 40 | + MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); |
| 41 | + |
| 42 | + String expectedOutput = new GsonBuilder() |
| 43 | + .setPrettyPrinting() |
| 44 | + .serializeNulls() |
| 45 | + .disableHtmlEscaping() |
| 46 | + .create() |
| 47 | + .toJson(new JsonParser() |
| 48 | + .parse("{\"imdbId\":null,\"actors\":[{\"<strong>IMDB Code</strong>\":\"nm2199632\",\"<strong>Date Of Birth</strong>\":\"21-09-1982\",\"<strong>N° Film:</strong> \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}]}")); |
| 49 | + Assert.assertEquals(gson.toJson(movieWithNullValue), expectedOutput); |
| 50 | + } |
| 51 | +} |
0 commit comments