• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.gson;
18 
19 import com.google.gson.reflect.TypeToken;
20 import java.lang.reflect.Type;
21 import java.util.HashMap;
22 import java.util.Map;
23 import junit.framework.TestCase;
24 
25 /**
26  * Unit test for the default JSON map serialization object located in the
27  * {@link DefaultTypeAdapters} class.
28  *
29  * @author Joel Leitch
30  */
31 public class DefaultMapJsonSerializerTest extends TestCase {
32   private Gson gson = new Gson();
33 
testEmptyMapNoTypeSerialization()34   public void testEmptyMapNoTypeSerialization() {
35     Map<String, String> emptyMap = new HashMap<>();
36     JsonElement element = gson.toJsonTree(emptyMap, emptyMap.getClass());
37     assertTrue(element instanceof JsonObject);
38     JsonObject emptyMapJsonObject = (JsonObject) element;
39     assertTrue(emptyMapJsonObject.entrySet().isEmpty());
40   }
41 
testEmptyMapSerialization()42   public void testEmptyMapSerialization() {
43     Type mapType = new TypeToken<Map<String, String>>() { }.getType();
44     Map<String, String> emptyMap = new HashMap<>();
45     JsonElement element = gson.toJsonTree(emptyMap, mapType);
46 
47     assertTrue(element instanceof JsonObject);
48     JsonObject emptyMapJsonObject = (JsonObject) element;
49     assertTrue(emptyMapJsonObject.entrySet().isEmpty());
50   }
51 
testNonEmptyMapSerialization()52   public void testNonEmptyMapSerialization() {
53     Type mapType = new TypeToken<Map<String, String>>() { }.getType();
54     Map<String, String> myMap = new HashMap<>();
55     String key = "key1";
56     myMap.put(key, "value1");
57     Gson gson = new Gson();
58     JsonElement element = gson.toJsonTree(myMap, mapType);
59 
60     assertTrue(element.isJsonObject());
61     JsonObject mapJsonObject = element.getAsJsonObject();
62     assertTrue(mapJsonObject.has(key));
63   }
64 }
65