You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JsonUtilsTest.java 2.0KB

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