James Moger
2012-10-01 eb1405f736f2f98e14215774dd53eea9b9a77017
commit | author | age
143fc9 1 /*
JM 2  * Copyright 2011 gitblit.com.
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 package com.gitblit.tests;
17
7e8873 18 import static org.junit.Assert.assertEquals;
JM 19
143fc9 20 import java.text.SimpleDateFormat;
JM 21 import java.util.Date;
22 import java.util.HashMap;
23 import java.util.Map;
24
7e8873 25 import org.junit.Test;
143fc9 26
JM 27 import com.gitblit.utils.JsonUtils;
28 import com.google.gson.reflect.TypeToken;
29
7e8873 30 public class JsonUtilsTest {
143fc9 31
7e8873 32     @Test
143fc9 33     public void testSerialization() {
JM 34         Map<String, String> map = new HashMap<String, String>();
35         map.put("a", "alligator");
36         map.put("b", "bear");
37         map.put("c", "caterpillar");
38         map.put("d", "dingo");
39         map.put("e", "eagle");
40         String json = JsonUtils.toJsonString(map);
41         assertEquals(
42                 "{\n  \"d\": \"dingo\",\n  \"e\": \"eagle\",\n  \"b\": \"bear\",\n  \"c\": \"caterpillar\",\n  \"a\": \"alligator\"\n}",
43                 json);
44         Map<String, String> map2 = JsonUtils.fromJsonString(json,
45                 new TypeToken<Map<String, String>>() {
46                 }.getType());
47         assertEquals(map, map2);
48
49         SomeJsonObject someJson = new SomeJsonObject();
50         json = JsonUtils.toJsonString(someJson);
51         SomeJsonObject someJson2 = JsonUtils.fromJsonString(json, SomeJsonObject.class);
52         assertEquals(someJson.name, someJson2.name);
53         SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");
54         assertEquals(df.format(someJson.date), df.format(someJson2.date));
55     }
56
57     private class SomeJsonObject {
58         Date date = new Date();
59         String name = "myJson";
60     }
61 }