MCPcopy
hub / github.com/google/gson / MapTest

Class MapTest

src/test/java/com/google/gson/functional/MapTest.java:43–398  ·  view source on GitHub ↗

Functional test for Json serialization and deserialization for Maps @author Inderjeet Singh @author Joel Leitch

Source from the content-addressed store, hash-verified

41 * @author Joel Leitch
42 */
43public class MapTest extends TestCase {
44 private Gson gson;
45
46 @Override
47 protected void setUp() throws Exception {
48 super.setUp();
49 gson = new Gson();
50 }
51
52 public void testMapSerialization() {
53 Map<String, Integer> map = new LinkedHashMap<String, Integer>();
54 map.put("a", 1);
55 map.put("b", 2);
56 Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
57 String json = gson.toJson(map, typeOfMap);
58 assertTrue(json.contains("\"a\":1"));
59 assertTrue(json.contains("\"b\":2"));
60 }
61
62 public void testMapDeserialization() {
63 String json = "{\"a\":1,\"b\":2}";
64 Type typeOfMap = new TypeToken<Map<String,Integer>>(){}.getType();
65 Map<String, Integer> target = gson.fromJson(json, typeOfMap);
66 assertEquals(1, target.get("a").intValue());
67 assertEquals(2, target.get("b").intValue());
68 }
69
70 @SuppressWarnings("unchecked")
71 public void testRawMapSerialization() {
72 Map map = new LinkedHashMap();
73 map.put("a", 1);
74 map.put("b", "string");
75 String json = gson.toJson(map);
76 assertTrue(json.contains("\"a\":1"));
77 assertTrue(json.contains("\"b\":\"string\""));
78 }
79
80 public void testMapSerializationEmpty() {
81 Map<String, Integer> map = new LinkedHashMap<String, Integer>();
82 Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
83 String json = gson.toJson(map, typeOfMap);
84 assertEquals("{}", json);
85 }
86
87 public void testMapDeserializationEmpty() {
88 Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
89 Map<String, Integer> map = gson.fromJson("{}", typeOfMap);
90 assertTrue(map.isEmpty());
91 }
92
93 public void testMapSerializationWithNullValue() {
94 Map<String, Integer> map = new LinkedHashMap<String, Integer>();
95 map.put("abc", null);
96 Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
97 String json = gson.toJson(map, typeOfMap);
98
99 // Maps are represented as JSON objects, so ignoring null field
100 assertEquals("{}", json);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected