@Override public void serialize(TypeToken<?> type, Text obj, ConfigurationNode value) throws ObjectMappingException { String json = (String) obj.toContainer().get(Queries.JSON).get(); GsonConfigurationLoader gsonLoader = GsonConfigurationLoader.builder() .setSource(() -> new BufferedReader(new StringReader(json))) .build(); try { value.setValue(gsonLoader.load()); } catch (IOException e) { throw new ObjectMappingException(e); } }
@Override public void serialize(TypeToken<?> type, Text obj, ConfigurationNode value) throws ObjectMappingException { String json = (String) obj.toContainer().get(Queries.JSON).get(); GsonConfigurationLoader gsonLoader = GsonConfigurationLoader.builder() .setSource(() -> new BufferedReader(new StringReader(json))) .build(); try { value.setValue(gsonLoader.load()); } catch (IOException e) { throw new ObjectMappingException(e); } }
@Test public void testLoadingFileWithEmptyObject(@TempDirectory.TempDir Path tempDir) throws IOException { URL url = getClass().getResource("/emptyObject.json"); final Path tempFile = tempDir.resolve("text4.txt"); ConfigurationLoader<ConfigurationNode> loader = GsonConfigurationLoader.builder() .setSource(() -> new BufferedReader(new InputStreamReader(url.openStream()))) .setSink(AtomicFiles.createAtomicWriterFactory(tempFile, UTF_8)).setLenient(true).build(); ConfigurationNode node = loader.load(loader.getDefaultOptions().setMapFactory(MapFactories.sortedNatural())); assertNull(node.getValue()); assertFalse(node.hasMapChildren()); }
@Test public void testSimpleLoading(@TempDirectory.TempDir Path tempDir) throws IOException { URL url = getClass().getResource("/example.json"); final Path tempFile = tempDir.resolve("text1.txt"); ConfigurationLoader<ConfigurationNode> loader = GsonConfigurationLoader.builder() .setSource(() -> new BufferedReader(new InputStreamReader(url.openStream()))) .setSink(AtomicFiles.createAtomicWriterFactory(tempFile, UTF_8)).setLenient(true).build(); ConfigurationNode node = loader.load(loader.getDefaultOptions().setMapFactory(MapFactories.sortedNatural())); assertEquals("unicorn", node.getNode("test", "op-level").getValue()); assertEquals("dragon", node.getNode("other", "op-level").getValue()); assertEquals("dog park", node.getNode("other", "location").getValue()); assertTrue(node.getNode("int-val").getValue() instanceof Integer); assertTrue(node.getNode("double-val").getValue() instanceof Double); loader.save(node); assertEquals(Resources.readLines(url, UTF_8), Files.readAllLines(tempFile, UTF_8)); }