1+ package org .baeldung .gson .serialization ;
2+
3+ import static org .junit .Assert .assertEquals ;
4+
5+ import java .lang .reflect .Type ;
6+ import java .util .Collection ;
7+
8+ import org .junit .Test ;
9+
10+ import com .google .common .collect .Lists ;
11+ import com .google .gson .Gson ;
12+ import com .google .gson .GsonBuilder ;
13+ import com .google .gson .reflect .TypeToken ;
14+
15+ public class GsonSerializationTest {
16+
17+ @ Test
18+ public void givenCollection_whenSerializing_thenCorrect () {
19+ final Collection <SourceClass > sourceCollection = Lists .newArrayList (new SourceClass (1 , "one" ), new SourceClass (2 , "two" ));
20+ final Type sourceCollectionType = new TypeToken <Collection <SourceClass >>() {
21+ }.getType ();
22+ final String jsonCollection = new Gson ().toJson (sourceCollection , sourceCollectionType );
23+
24+ // test
25+ final Collection <SourceClass > testCollection = new Gson ().fromJson (jsonCollection , sourceCollectionType );
26+ assertEquals (sourceCollection , testCollection );
27+ }
28+
29+ @ Test
30+ public void givenArrayOfObjects_whenSerializing_thenMapToJsonCollection () {
31+ final SourceClass [] sourceArray = { new SourceClass (1 , "one" ), new SourceClass (2 , "two" ) };
32+ final String jsonCollection = new Gson ().toJson (sourceArray );
33+
34+ // test
35+ final String estimatedResult = "[{\" intValue\" :1,\" stringValue\" :\" one\" },{\" intValue\" :2,\" stringValue\" :\" two\" }]" ;
36+ assertEquals (estimatedResult , jsonCollection );
37+ }
38+
39+ @ Test
40+ public void givenUsingCustomSerializer_whenSerializingObjectToJsonWithDissimilarFieldNames_thenCorrect () {
41+ final SourceClass sourceObject = new SourceClass (7 , "seven" );
42+ final GsonBuilder gsonBuildr = new GsonBuilder ();
43+ gsonBuildr .registerTypeAdapter (SourceClass .class , new SourceClassChangingFieldNamesSerializer ());
44+ final Gson gson = gsonBuildr .create ();
45+ final String jsonString = gson .toJson (sourceObject );
46+
47+ // test
48+ final String estimatedResult = "{\" otherIntValue\" :7,\" otherStringValue\" :\" seven\" }" ;
49+ assertEquals (estimatedResult , jsonString );
50+ }
51+
52+ @ Test
53+ public void givenUsingCustomSerializer_whenSerializingObject_thenFieldIgnored () {
54+ final SourceClass sourceObject = new SourceClass (7 , "seven" );
55+ final GsonBuilder gsonBuildr = new GsonBuilder ();
56+ gsonBuildr .registerTypeAdapter (SourceClass .class , new SourceClassIgnoringExtraFieldsSerializer ());
57+ final Gson gson = gsonBuildr .create ();
58+ final String jsonString = gson .toJson (sourceObject );
59+
60+ // test
61+ final String estimatedResult = "{\" intValue\" :7}" ;
62+ assertEquals (estimatedResult , jsonString );
63+ }
64+ }
0 commit comments