AndroidJsonHandler implements KeenJsonHandler { @Override public Map<String, Object> readJson(Reader reader) throws IOException { if (reader == null) { throw new IllegalArgumentException("Reader must not be null"); } String json = readerToString(reader); try { Object jsonObjOrArray = getJsonObjectManager().newTokener(json).nextValue(); Object rootNode = JsonHelper.fromJson(jsonObjOrArray); Map<String, Object> rootMap = null; if (null == rootNode) { throw new IllegalArgumentException("Empty reader or ill-formatted JSON " + "encountered."); } else if (rootNode instanceof Map) { rootMap = (Map)rootNode; } else if (rootNode instanceof List) { rootMap = new LinkedHashMap<String, Object>(); rootMap.put(KeenConstants.KEEN_FAKE_JSON_ROOT, rootNode); } return rootMap; } catch (JSONException e) { throw new IOException(e); } }  @Override Map<String, Object> readJson(Reader reader); @Override void writeJson(Writer writer, Map<String, ?> value); void setWrapNestedMapsAndCollections(boolean value);  }
@Test public void readSimpleMap() throws Exception { JSONObject mockJsonObject = mock(JSONObject.class); List<String> keys = Arrays.asList("result"); when(mockJsonObject.keys()).thenReturn(keys.iterator()); when(mockJsonObject.get("result")).thenReturn("dummyResult"); JSONTokener mockJsonTokener = mock(JSONTokener.class); when(mockJsonTokener.nextValue()).thenReturn(mockJsonObject); when(mockJsonObjectManager.newTokener(anyString())).thenReturn(mockJsonTokener); String mapResponse = "{\"result\": \"dummyResult\"}"; StringReader reader = new StringReader(mapResponse); Map<String, Object> map = handler.readJson(reader); assertNotNull(map); assertEquals(1, map.size()); assertTrue(map.containsKey("result")); assertEquals("dummyResult", map.get("result")); }
@Test public void readSimpleList() throws Exception { JSONArray mockJsonArray = mock(JSONArray.class); when(mockJsonArray.length()).thenReturn(1); when(mockJsonArray.get(0)).thenReturn("dummyResult"); JSONTokener mockJsonTokener = mock(JSONTokener.class); when(mockJsonTokener.nextValue()).thenReturn(mockJsonArray); when(mockJsonObjectManager.newTokener(anyString())).thenReturn(mockJsonTokener); String listResponse = "[\"dummyResult\"]"; StringReader reader = new StringReader(listResponse); Map<String, Object> map = handler.readJson(reader); assertNotNull(map); assertEquals(1, map.size()); assertTrue(map.containsKey(KeenConstants.KEEN_FAKE_JSON_ROOT)); Object jsonArrayObj = map.get(KeenConstants.KEEN_FAKE_JSON_ROOT); assertNotNull(jsonArrayObj); assertTrue(jsonArrayObj instanceof List); assertEquals(1, ((List)jsonArrayObj).size()); assertEquals("dummyResult", ((List)jsonArrayObj).get(0)); }