Skip to content

Commit

Permalink
better exception message for non-String keys in yaml
Browse files Browse the repository at this point in the history
  • Loading branch information
Fallen-Breath committed Nov 15, 2023
1 parent fdf5466 commit 349fb8b
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/main/java/me/fallenbreath/yamlang/Yamlang2JsonlangMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,33 +21,39 @@ public Yamlang2JsonlangMapper(Reader reader) throws IOException

private static String yamlang2Jsonlang(String ymlContent)
{
Map<String, Object> yamlMap = new Yaml().load(ymlContent);
Map<Object, Object> yamlMap = new Yaml().load(ymlContent);
Map<String, String> result = new LinkedHashMap<>();
parseMap(result, yamlMap, "");
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
return gson.toJson(result);
}

@SuppressWarnings("unchecked")
private static void parseMap(Map<String, String> result, Map<String, Object> yamlMap, String prefix)
private static void parseMap(Map<String, String> result, Map<Object, Object> yamlMap, String prefix)
{
yamlMap.forEach((key, value) -> {
yamlMap.forEach((keyObj, value) -> {
if (value == null)
{
return;
}
if (!(keyObj instanceof String))
{
throw new IllegalArgumentException(String.format("Bad type %s for key %s at path %s", keyObj.getClass(), keyObj, prefix));
}

String key = (String)keyObj;
String fullKey = prefix.isEmpty() ? key : (!key.equals(".") ? prefix + "." + key : prefix);
if (value instanceof String)
{
result.put(fullKey, (String) value);
}
else if (value instanceof Map)
{
parseMap(result, (Map<String, Object>)value, fullKey);
parseMap(result, (Map<Object, Object>)value, fullKey);
}
else
{
throw new RuntimeException(String.format("Unknown type %s in with key %s", value.getClass(), fullKey));
throw new IllegalArgumentException(String.format("Unknown type %s in with key %s", value.getClass(), fullKey));
}
});
}
Expand Down

0 comments on commit 349fb8b

Please sign in to comment.