Clarify how to serialise a top-level table array.

Fixes #35
This commit is contained in:
Moandji Ezana 2016-07-18 08:43:28 +02:00
parent bede018b3d
commit 644c23f17d
2 changed files with 35 additions and 4 deletions

View file

@ -245,7 +245,9 @@ toml.containsTableArray("a"); // false
### Converting Objects To TOML ### Converting Objects To TOML
You can write any arbitrary object to a TOML `String`, `File`, `Writer`, or `OutputStream` with a `TomlWriter`. Each TomlWriter instance is customisable, immutable and threadsafe, so it can be reused and passed around. Constants and transient fields are ignored. You can write `Map`s and custom objects to a TOML `String`, `File`, `Writer`, or `OutputStream` with a `TomlWriter`. Each TomlWriter instance is customisable, immutable and threadsafe, so it can be reused and passed around. Constants and transient fields are ignored.
To write a `List` of objects as a table array, put the list in a `Map` or in a custom object.
```java ```java
class AClass { class AClass {

View file

@ -14,6 +14,7 @@ import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
@ -168,7 +169,7 @@ public class TomlWriterTest {
} }
@Test @Test
public void should_write_array_of_tables() { public void should_write_array_of_tables_from_object() {
class Table { class Table {
int anInt; int anInt;
@ -177,15 +178,43 @@ public class TomlWriterTest {
} }
} }
class Config { class Config {
Table[] table; Table[] table = new Table[]{new Table(1), new Table(2)};
List<Table> table2 = Arrays.asList(new Table(3), new Table(4));
} }
Config config = new Config(); Config config = new Config();
config.table = new Table[]{new Table(1), new Table(2)};
String output = new TomlWriter().write(config); String output = new TomlWriter().write(config);
String expected = "[[table]]\n" + String expected = "[[table]]\n" +
"anInt = 1\n\n" + "anInt = 1\n\n" +
"[[table]]\n" + "[[table]]\n" +
"anInt = 2\n" +
"[[table2]]\n" +
"anInt = 3\n\n" +
"[[table2]]\n" +
"anInt = 4\n";
assertEquals(expected, output);
}
@Test
public void should_write_array_of_tables_from_map() throws Exception {
List<Map<String, Object>> maps = new ArrayList<Map<String,Object>>();
HashMap<String, Object> item1 = new HashMap<String, Object>();
item1.put("anInt", 1L);
HashMap<String, Object> item2 = new HashMap<String, Object>();
item2.put("anInt", 2L);
maps.add(item1);
maps.add(item2);
Map<String, Object> input = new HashMap<String, Object>();
input.put("maps", maps);
String output = new TomlWriter().write(input);
String expected = "[[maps]]\n" +
"anInt = 1\n\n" +
"[[maps]]\n" +
"anInt = 2\n"; "anInt = 2\n";
assertEquals(expected, output); assertEquals(expected, output);
} }