mirror of
https://github.com/songoda/SongodaCore.git
synced 2025-02-17 03:51:27 +01:00
Fix YamlConfiguration dumping null values and empty tree nodes
This commit is contained in:
parent
885cc9a87e
commit
02ab8d4bb2
@ -209,6 +209,8 @@ public class YamlConfiguration implements IConfiguration, HeaderCommentable, Nod
|
||||
String headerCommentLines = generateHeaderCommentLines();
|
||||
writer.write(headerCommentLines);
|
||||
|
||||
cleanValuesMap(this.values);
|
||||
|
||||
if (this.values.size() > 0) {
|
||||
if (headerCommentLines.length() > 0) {
|
||||
writer.write(this.yamlDumperOptions.getLineBreak().getString());
|
||||
@ -343,4 +345,23 @@ public class YamlConfiguration implements IConfiguration, HeaderCommentable, Nod
|
||||
++currentKeyIndex;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This takes a map and removes all keys that have a value of null.<br>
|
||||
* Additionally, if the value is a {@link Map}, it will be recursively cleaned too.<br>
|
||||
* {@link Map}s that are or get empty, will be removed (recursively).<br>
|
||||
*/
|
||||
protected void cleanValuesMap(Map<?, ?> map) {
|
||||
for (Object key : map.keySet().toArray()) {
|
||||
Object value = map.get(key);
|
||||
|
||||
if (value instanceof Map) {
|
||||
cleanValuesMap((Map<?, ?>) value);
|
||||
}
|
||||
|
||||
if (value == null || (value instanceof Map && ((Map<?, ?>) value).isEmpty())) {
|
||||
map.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -139,6 +139,19 @@ class YamlConfigurationTest {
|
||||
assertEquals(expectedOutYaml, cfg.toYamlString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testYamlWriterWithNullValue() throws IOException {
|
||||
final YamlConfiguration cfg = new YamlConfiguration();
|
||||
final StringWriter stringWriter = new StringWriter(1);
|
||||
|
||||
cfg.set("null-value", null);
|
||||
cfg.set("nested.null-value", null);
|
||||
cfg.save(stringWriter);
|
||||
|
||||
assertEquals("", stringWriter.toString());
|
||||
assertEquals("", cfg.toYamlString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testYamlWriterWithNoData() throws IOException {
|
||||
final YamlConfiguration cfg = new YamlConfiguration();
|
||||
@ -239,6 +252,16 @@ class YamlConfigurationTest {
|
||||
assertEquals("value", cfg.get("primitives.map.key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetterWithNullValue() {
|
||||
final YamlConfiguration cfg = new YamlConfiguration();
|
||||
|
||||
assertNull(cfg.set("foo.bar.null", "not-null-string"));
|
||||
assertEquals("not-null-string", cfg.set("foo.bar.null", null));
|
||||
|
||||
assertNull(cfg.get("foo.bar.null"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetNonExistingNestedKey() {
|
||||
final YamlConfiguration cfg = new YamlConfiguration();
|
||||
|
Loading…
Reference in New Issue
Block a user