From 65dfd502c85b8def3dc9010065a722a1e7425715 Mon Sep 17 00:00:00 2001 From: AoEiuV020 Date: Tue, 22 May 2018 20:23:53 +0800 Subject: [PATCH] Passing ParameterizedType to Parser --- .../com/orhanobut/hawk/HawkConverter.java | 33 +++---------------- .../hawk/HawkFacadeIntegrationTest.java | 12 ++++++- 2 files changed, 16 insertions(+), 29 deletions(-) diff --git a/hawk/src/main/java/com/orhanobut/hawk/HawkConverter.java b/hawk/src/main/java/com/orhanobut/hawk/HawkConverter.java index 05a37e5..4a5a19e 100644 --- a/hawk/src/main/java/com/orhanobut/hawk/HawkConverter.java +++ b/hawk/src/main/java/com/orhanobut/hawk/HawkConverter.java @@ -68,14 +68,8 @@ private T toList(String json, Class type) throws Exception { } List list = parser.fromJson( json, - new TypeToken>() { - }.getType() + TypeToken.getParameterized(List.class, type).getType() ); - - int size = list.size(); - for (int i = 0; i < size; i++) { - list.set(i, (T) parser.fromJson(parser.toJson(list.get(i)), type)); - } return (T) list; } @@ -85,15 +79,8 @@ private T toSet(String json, Class type) throws Exception { if (type == null) { return (T) resultSet; } - Set set = parser.fromJson(json, new TypeToken>() { - }.getType()); - - for (T t : set) { - String valueJson = parser.toJson(t); - T value = parser.fromJson(valueJson, type); - resultSet.add(value); - } - return (T) resultSet; + Set set = parser.fromJson(json, TypeToken.getParameterized(Set.class, type).getType()); + return (T) set; } @SuppressWarnings("unchecked") @@ -102,18 +89,8 @@ private T toMap(String json, Class keyType, Class valueType) thr if (keyType == null || valueType == null) { return (T) resultMap; } - Map map = parser.fromJson(json, new TypeToken>() { - }.getType()); - - for (Map.Entry entry : map.entrySet()) { - String keyJson = parser.toJson(entry.getKey()); - K k = parser.fromJson(keyJson, keyType); - - String valueJson = parser.toJson(entry.getValue()); - V v = parser.fromJson(valueJson, valueType); - resultMap.put(k, v); - } - return (T) resultMap; + Map map = parser.fromJson(json, TypeToken.getParameterized(Map.class, keyType, valueType).getType()); + return (T) map; } } diff --git a/hawk/src/test/java/com/orhanobut/hawk/HawkFacadeIntegrationTest.java b/hawk/src/test/java/com/orhanobut/hawk/HawkFacadeIntegrationTest.java index fa0c90c..76006b7 100644 --- a/hawk/src/test/java/com/orhanobut/hawk/HawkFacadeIntegrationTest.java +++ b/hawk/src/test/java/com/orhanobut/hawk/HawkFacadeIntegrationTest.java @@ -87,6 +87,17 @@ public class HawkFacadeIntegrationTest { assertThat(list1).isNotNull(); } + @Test public void testBeanList() { + List list = new ArrayList<>(); + list.add(new FooBar()); + Hawk.put("tag", list); + + List list1 = Hawk.get("tag"); + + assertThat(list1).isNotNull(); + assertThat(list1.get(0).getName()).isEqualTo("hawk"); + } + @Test public void testMap() { Map map = new HashMap<>(); map.put("key", "value"); @@ -178,5 +189,4 @@ public class HawkFacadeIntegrationTest { } assertThat(true).isTrue(); } - }