From d9e1ccc98a36a10941237319628c86c6911f3bc9 Mon Sep 17 00:00:00 2001 From: "moandji.ezana" Date: Tue, 22 Jul 2014 15:50:39 +0200 Subject: [PATCH] Added Toml#to(Class, Gson) to allow for test output as specified by BurntSushi/toml-test --- src/main/java/com/moandjiezana/toml/Toml.java | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/moandjiezana/toml/Toml.java b/src/main/java/com/moandjiezana/toml/Toml.java index 5a96182..deaac0c 100644 --- a/src/main/java/com/moandjiezana/toml/Toml.java +++ b/src/main/java/com/moandjiezana/toml/Toml.java @@ -26,6 +26,7 @@ import org.parboiled.parserunners.RecoveringParseRunner; import org.parboiled.support.ParsingResult; import com.google.gson.Gson; +import com.google.gson.JsonElement; /** *

Provides access to the keys and tables in a TOML data source.

@@ -46,10 +47,11 @@ import com.google.gson.Gson; */ public class Toml { - private static Pattern ARRAY_INDEX_PATTERN = Pattern.compile("(.*)\\[(\\d+)\\]"); + private static final Gson DEFAULT_GSON = new Gson(); + private static final Pattern ARRAY_INDEX_PATTERN = Pattern.compile("(.*)\\[(\\d+)\\]"); + private Map values = new HashMap(); private final Toml defaults; - private final Gson gson = new Gson(); /** * Creates Toml instance with no defaults. @@ -223,6 +225,13 @@ public class Toml { * @param targetClass */ public T to(Class targetClass) { + return to(targetClass, DEFAULT_GSON); + } + + /* + * Should not be used directly, except for testing purposes + */ + T to(Class targetClass, Gson gson) { HashMap valuesCopy = new HashMap(values); if (defaults != null) { @@ -233,7 +242,12 @@ public class Toml { } } - String json = gson.toJson(valuesCopy); + JsonElement json = gson.toJsonTree(valuesCopy); + + if (targetClass == JsonElement.class) { + return targetClass.cast(json); + } + return gson.fromJson(json, targetClass); }