JsonWriter implements DataWriter<JsonWriteOptions> { public void write(Table table, JsonWriteOptions options) throws IOException { ArrayNode output = mapper.createArrayNode(); if (options.asObjects()) { for (int r = 0; r < table.rowCount(); r++) { ObjectNode row = mapper.createObjectNode(); for (int c = 0; c < table.columnCount(); c++) { row.set(table.column(c).name(), mapper.convertValue(table.get(r, c), JsonNode.class)); } output.add(row); } } else { if (options.header()) { ArrayNode row = mapper.createArrayNode(); for (int c = 0; c < table.columnCount(); c++) { row.add(mapper.convertValue(table.column(c).name(), JsonNode.class)); } output.add(row); } for (int r = 0; r < table.rowCount(); r++) { ArrayNode row = mapper.createArrayNode(); for (int c = 0; c < table.columnCount(); c++) { row.add(mapper.convertValue(table.get(r, c), JsonNode.class)); } output.add(row); } } String str = mapper.writeValueAsString(output); try (Writer writer = options.destination().createWriter()) { writer.write(str); } }  static void register(WriterRegistry registry); void write(Table table, JsonWriteOptions options); @Override void write(Table table, Destination dest);  }
@Test public void arrayOfArraysWithHeader() throws IOException { String json = "[[\"Date\",\"Value\"],[1453438800000,-2.144],[1454043600000,-2.976],[1454648400000,-2.9541]]"; Table table = Table.read().string(json, "json"); StringWriter writer = new StringWriter(); table .write() .usingOptions(JsonWriteOptions.builder(writer).asObjects(false).header(true).build()); assertEquals(json, writer.toString()); }
@Test public void arrayOfArraysNoHeader() throws IOException { String json = "[[1453438800000,-2.144],[1454043600000,-2.976],[1454648400000,-2.954]]"; Table table = Table.read().string(json, "json"); StringWriter writer = new StringWriter(); table .write() .usingOptions(JsonWriteOptions.builder(writer).asObjects(false).header(false).build()); assertEquals(json, writer.toString()); }
@Test public void arrayOfObjects() { String json = "[{\"a\":1453438800000,\"b\":-2.144},{\"a\":1454043600000,\"b\":-2.976},{\"a\":1454648400000,\"b\":-2.954}]"; Table table = Table.read().string(json, "json"); String output = table.write().toString("json"); assertEquals(json, output); }