1 package org.djutils.data.json;
2
3 import java.io.FileReader;
4 import java.io.FileWriter;
5 import java.io.IOException;
6 import java.io.Reader;
7 import java.io.Writer;
8 import java.util.ArrayList;
9 import java.util.IllegalFormatException;
10 import java.util.List;
11
12 import org.djutils.data.DataColumn;
13 import org.djutils.data.DataRecord;
14 import org.djutils.data.DataTable;
15 import org.djutils.data.ListDataTable;
16 import org.djutils.data.SimpleDataColumn;
17 import org.djutils.data.serialization.TextSerializationException;
18 import org.djutils.data.serialization.TextSerializer;
19 import org.djutils.exceptions.Throw;
20 import org.djutils.primitives.Primitive;
21
22 import com.google.gson.stream.JsonReader;
23 import com.google.gson.stream.JsonToken;
24 import com.google.gson.stream.JsonWriter;
25
26 /**
27 * JSONData takes care of reading and writing of table data in JSON format. The reader and writer use a streaming API to avoid
28 * excessive memory use. The class can be used, e.g., as follows:
29 *
30 * <pre>
31 * DataTable dataTable = new ListDataTable("data", "dataTable", columns);
32 * Writer writer = new FileWriter("c:/data/data.json");
33 * JSONData.writeData(writer, dataTable);
34 * </pre>
35 *
36 * The JSON document has the following structure:
37 *
38 * <pre>
39 * {
40 * "table": {
41 * "id": "tableId",
42 * "description": "table description",
43 * "class": "org.djutils.data.ListDataTable"",
44 * "columns": [
45 * {
46 * "nr": "0",
47 * "id": "time",
48 * "description": "time in [s]",
49 * "class": "org.djtils.vdouble.scalar.Time",
50 * },
51 * {
52 * "nr": "1",
53 * "id": "value",
54 * "description": "value [cm]",
55 * "class": "double",
56 * },
57 * {
58 * "nr": "2",
59 * "id": "comment",
60 * "description": "comment",
61 * "class": "java.lang.String",
62 * },
63 * ]
64 * },
65 * "data": [
66 * [ { "0" : "2" }, { "1": "14.6" }, { "2" : "normal" } ],
67 * [ { "0" : "4" }, { "1": "18.7" }, { "2" : "normal" } ],
68 * [ { "0" : "6" }, { "1": "21.3" }, { "2" : "abnormal" } ]
69 * ]
70 * }
71 * </pre>
72 *
73 * Copyright (c) 2020-2020 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
74 * for project information <a href="https://djutils.org" target="_blank"> https://djutils.org</a>. The DJUTILS project is
75 * distributed under a three-clause BSD-style license, which can be found at
76 * <a href="https://djutils.org/docs/license.html" target="_blank"> https://djutils.org/docs/license.html</a>. <br>
77 * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a>
78 * @author <a href="https://www.tudelft.nl/pknoppers">Peter Knoppers</a>
79 * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
80 */
81 public final class JSONData
82 {
83 /**
84 * Utility class, no public constructor.
85 */
86 private JSONData()
87 {
88 // utility class
89 }
90
91 /**
92 * Write the data from the data table in JSON format.
93 * @param writer Writer; the writer that writes the data, e.g. to a file
94 * @param dataTable DataTable; the data table to write
95
96 * @throws IOException on I/O error when writing the data
97 * @throws TextSerializationException on unknown data type for serialization
98 */
99 public static void writeData(final Writer writer, final DataTable dataTable) throws IOException, TextSerializationException
100 {
101 JsonWriter jw = null;
102 try
103 {
104 jw = new JsonWriter(writer);
105 jw.setIndent(" ");
106
107 // write the table metadata
108 jw.beginObject();
109 jw.name("table").beginObject();
110 jw.name("id").value(dataTable.getId());
111 jw.name("description").value(dataTable.getDescription());
112 jw.name("class").value(dataTable.getClass().getName());
113 jw.name("columns").beginArray();
114 int index = 0;
115 for (DataColumn<?> column : dataTable.getColumns())
116 {
117 jw.beginObject();
118 jw.name("nr").value(index++);
119 jw.name("id").value(column.getId());
120 jw.name("description").value(column.getDescription());
121 jw.name("type").value(column.getValueType().getName());
122 jw.endObject();
123 }
124 jw.endArray(); // columns
125 jw.endObject(); // table
126
127 // initialize the serializers
128 TextSerializer<?>[] serializers = new TextSerializer[dataTable.getNumberOfColumns()];
129 for (int i = 0; i < dataTable.getNumberOfColumns(); i++)
130 {
131 DataColumn<?> column = dataTable.getColumns().get(i);
132 serializers[i] = TextSerializer.resolve(column.getValueType());
133 }
134
135 // write the data
136 jw.name("data").beginArray();
137
138 // write the records
139 for (DataRecord record : dataTable)
140 {
141 Object[] values = record.getValues();
142 jw.beginArray();
143 jw.setIndent("");
144 for (int i = 0; i < dataTable.getNumberOfColumns(); i++)
145 {
146 jw.beginObject().name(String.valueOf(i)).value(serializers[i].serialize(values[i])).endObject();
147 }
148 jw.endArray(); // record
149 jw.setIndent(" ");
150 }
151
152 // end JSON document
153 jw.endArray(); // data array
154 jw.endObject(); // data
155 }
156 finally
157 {
158 if (null != jw)
159 {
160 jw.close();
161 }
162 }
163 }
164
165 /**
166 * Write the data from the data table in JSON format.
167 * @param filename String; the file name to write the data to
168 * @param dataTable DataTable; the data table to write
169
170 * @throws IOException on I/O error when writing the data
171 * @throws TextSerializationException on unknown data type for serialization
172 */
173 public static void writeData(final String filename, final DataTable dataTable)
174 throws IOException, TextSerializationException
175 {
176 FileWriter fw = null;
177 try
178 {
179 fw = new FileWriter(filename);
180 writeData(fw, dataTable);
181 }
182 finally
183 {
184 if (null != fw)
185 {
186 fw.close();
187 }
188 }
189 }
190
191 /**
192 * Read the data from the csv-file into the data table. Use the metadata to reconstruct the data table.
193 * @param reader Reader; the reader that can read the data, e.g. from a file
194 * @return dataTable the data table reconstructed from the meta data and filled with the data
195 * @throws IOException on I/O error when reading the data
196 * @throws TextSerializationException on unknown data type for serialization
197 */
198 public static DataTable readData(final Reader reader) throws IOException, TextSerializationException
199 {
200 JsonReader jr = null;
201 try
202 {
203 // read the metadata and reconstruct the data table
204 jr = new JsonReader(reader);
205 jr.beginObject();
206 readName(jr, "table");
207 jr.beginObject();
208 String[] tableProperties = new String[3];
209 tableProperties[0] = readValue(jr, "id");
210 tableProperties[1] = readValue(jr, "description");
211 tableProperties[2] = readValue(jr, "class");
212 Throw.when(!tableProperties[2].endsWith("ListDataTable"), IOException.class,
213 "Currently, this method can only recreate a ListDataTable");
214
215 // column metadata
216 List<DataColumn<?>> columns = new ArrayList<>();
217 int index = 0;
218 readName(jr, "columns");
219 jr.beginArray();
220 while (jr.peek().equals(JsonToken.BEGIN_OBJECT))
221 {
222 String[] columnProperties = new String[4];
223 jr.beginObject();
224 columnProperties[0] = readValue(jr, "nr");
225 columnProperties[1] = readValue(jr, "id");
226 columnProperties[2] = readValue(jr, "description");
227 columnProperties[3] = readValue(jr, "type");
228 jr.endObject();
229
230 if (Integer.valueOf(columnProperties[0]).intValue() != index)
231 {
232 throw new IOException("column nr not ok");
233 }
234 String type = columnProperties[3];
235 Class<?> valueClass = Primitive.forName(type);
236 if (valueClass == null)
237 {
238 try
239 {
240 valueClass = Class.forName(type);
241 }
242 catch (ClassNotFoundException exception)
243 {
244 throw new IOException("Could not find class " + type, exception);
245 }
246 }
247 @SuppressWarnings({ "rawtypes", "unchecked" })
248 DataColumn<?> column = new SimpleDataColumn(columnProperties[1], columnProperties[2], valueClass);
249 columns.add(column);
250 index++;
251 }
252 jr.endArray(); // columns
253 jr.endObject(); // table
254
255 ListDataTablestDataTable">ListDataTable dataTable = new ListDataTable(tableProperties[0], tableProperties[1], columns);
256
257 // obtain the serializers
258 TextSerializer<?>[] serializers = new TextSerializer[dataTable.getNumberOfColumns()];
259 for (int i = 0; i < dataTable.getNumberOfColumns(); i++)
260 {
261 DataColumn<?> column = dataTable.getColumns().get(i);
262 serializers[i] = TextSerializer.resolve(column.getValueType());
263 }
264
265 // read the data file records
266 readName(jr, "data");
267 jr.beginArray();
268 while (jr.peek().equals(JsonToken.BEGIN_ARRAY))
269 {
270 Object[] values = new Object[columns.size()];
271 jr.beginArray();
272 for (int i = 0; i < dataTable.getNumberOfColumns(); i++)
273 {
274 jr.beginObject();
275 values[i] = serializers[i].deserialize(readValue(jr, "" + i));
276 jr.endObject();
277 }
278 jr.endArray(); // record
279 dataTable.addRecord(values);
280 }
281
282 // end JSON document
283 jr.endArray(); // data array
284 jr.endObject(); // data
285 return dataTable;
286 }
287 finally
288 {
289 if (null != jr)
290 {
291 jr.close();
292 }
293 }
294 }
295
296 /**
297 * Read a name - value pair from the JSON file where name has to match the given tag name.
298 * @param jr JsonReader; the JSON stream reader
299
300 * @param tag String; the tag to retrieve
301
302 * @return the value belonging to the tag
303 * @throws IllegalFormatException when the next element in the file did not contain the right tag
304 * @throws IOException when reading from the stream raises an exception
305 */
306 private static String readValue(final JsonReader jr, final String tag) throws IllegalFormatException, IOException
307 {
308 Throw.when(!jr.nextName().equals(tag), IllegalFormatException.class, "readValue: no %s object", tag);
309 return jr.nextString();
310 }
311
312 /**
313 * Read a name -from the JSON file where name has to match the given tag name.
314 * @param jr JsonReader; the JSON stream reader
315
316 * @param tag String; the tag to retrieve
317
318 * @throws IllegalFormatException when the next element in the file did not contain the right tag
319 * @throws IOException when reading from the stream raises an exception
320 */
321 private static void readName(final JsonReader jr, final String tag) throws IllegalFormatException, IOException
322 {
323 Throw.when(!jr.nextName().equals(tag), IllegalFormatException.class, "readName: no %s object", tag);
324 }
325
326 /**
327 * Read the data from the csv-file into the data table. Use the metadata to reconstruct the data table.
328 * @param filename String; the file name to read the data from
329 * @return dataTable the data table reconstructed from the meta data and filled with the data
330 * @throws IOException on I/O error when reading the data
331 * @throws TextSerializationException on unknown data type for serialization
332 */
333 public static DataTable readData(final String filename) throws IOException, TextSerializationException
334 {
335 FileReader fr = null;
336 try
337 {
338 fr = new FileReader(filename);
339 return readData(fr);
340 }
341 finally
342 {
343 if (null != fr)
344 {
345 fr.close();
346 }
347 }
348 }
349
350 }