View Javadoc
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   * &nbsp;&nbsp;"table": {
41   * &nbsp;&nbsp;&nbsp;&nbsp;"id": "tableId",
42   * &nbsp;&nbsp;&nbsp;&nbsp;"description": "table description",
43   * &nbsp;&nbsp;&nbsp;&nbsp;"class": "org.djutils.data.ListDataTable"",
44   * &nbsp;&nbsp;&nbsp;&nbsp;"columns": [
45   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
46   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"nr": "0",
47   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"id": "time",
48   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"description": "time in [s]",
49   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"class": "org.djtils.vdouble.scalar.Time",
50   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},
51   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
52   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"nr": "1",
53   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"id": "value",
54   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"description": "value [cm]",
55   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"class": "double",
56   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},
57   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{
58   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"nr": "2",
59   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"id": "comment",
60   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"description": "comment",
61   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"class": "java.lang.String",
62   * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;},
63   * &nbsp;&nbsp;&nbsp;&nbsp;] 
64   * &nbsp;&nbsp;},
65   * &nbsp;&nbsp;"data": [
66   * &nbsp;&nbsp;&nbsp;&nbsp;[ { "0" : "2" }, { "1": "14.6" }, { "2" : "normal" } ],   
67   * &nbsp;&nbsp;&nbsp;&nbsp;[ { "0" : "4" }, { "1": "18.7" }, { "2" : "normal" } ],   
68   * &nbsp;&nbsp;&nbsp;&nbsp;[ { "0" : "6" }, { "1": "21.3" }, { "2" : "abnormal" } ]
69   * &nbsp;&nbsp;]
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 the data table to write
95       * @throws IOException on I/O error when writing the data
96       * @throws TextSerializationException on unknown data type for serialization
97       */
98      public static void writeData(final Writer writer, final DataTable dataTable) throws IOException, TextSerializationException
99      {
100         JsonWriter jw = null;
101         try
102         {
103             jw = new JsonWriter(writer);
104             jw.setIndent("  ");
105 
106             // write the table metadata
107             jw.beginObject();
108             jw.name("table").beginObject();
109             jw.name("id").value(dataTable.getId());
110             jw.name("description").value(dataTable.getDescription());
111             jw.name("class").value(dataTable.getClass().getName());
112             jw.name("columns").beginArray();
113             int index = 0;
114             for (DataColumn<?> column : dataTable.getColumns())
115             {
116                 jw.beginObject();
117                 jw.name("nr").value(index++);
118                 jw.name("id").value(column.getId());
119                 jw.name("description").value(column.getDescription());
120                 jw.name("type").value(column.getValueType().getName());
121                 jw.endObject();
122             }
123             jw.endArray(); // columns
124             jw.endObject(); // table
125 
126             // initialize the serializers
127             TextSerializer<?>[] serializers = new TextSerializer[dataTable.getNumberOfColumns()];
128             for (int i = 0; i < dataTable.getNumberOfColumns(); i++)
129             {
130                 DataColumn<?> column = dataTable.getColumns().get(i);
131                 serializers[i] = TextSerializer.resolve(column.getValueType());
132             }
133 
134             // write the data
135             jw.name("data").beginArray();
136 
137             // write the records
138             for (DataRecord record : dataTable)
139             {
140                 Object[] values = record.getValues();
141                 jw.beginArray();
142                 jw.setIndent("");
143                 for (int i = 0; i < dataTable.getNumberOfColumns(); i++)
144                 {
145                     jw.beginObject().name(String.valueOf(i)).value(serializers[i].serialize(values[i])).endObject();
146                 }
147                 jw.endArray(); // record
148                 jw.setIndent("  ");
149             }
150 
151             // end JSON document
152             jw.endArray(); // data array
153             jw.endObject(); // data
154         }
155         finally
156         {
157             if (null != jw)
158             {
159                 jw.close();
160             }
161         }
162     }
163 
164     /**
165      * Write the data from the data table in JSON format.
166      * @param filename String; the file name to write the data to
167      * @param dataTable the data table to write
168      * @throws IOException on I/O error when writing the data
169      * @throws TextSerializationException on unknown data type for serialization
170      */
171     public static void writeData(final String filename, final DataTable dataTable)
172             throws IOException, TextSerializationException
173     {
174         FileWriter fw = null;
175         try
176         {
177             fw = new FileWriter(filename);
178             writeData(fw, dataTable);
179         }
180         finally
181         {
182             if (null != fw)
183             {
184                 fw.close();
185             }
186         }
187     }
188 
189     /**
190      * Read the data from the csv-file into the data table. Use the metadata to reconstruct the data table.
191      * @param reader Reader; the reader that can read the data, e.g. from a file
192      * @return dataTable the data table reconstructed from the meta data and filled with the data
193      * @throws IOException on I/O error when reading the data
194      * @throws TextSerializationException on unknown data type for serialization
195      */
196     public static DataTable readData(final Reader reader) throws IOException, TextSerializationException
197     {
198         JsonReader jr = null;
199         try
200         {
201             // read the metadata and reconstruct the data table
202             jr = new JsonReader(reader);
203             jr.beginObject();
204             readName(jr, "table");
205             jr.beginObject();
206             String[] tableProperties = new String[3];
207             tableProperties[0] = readValue(jr, "id");
208             tableProperties[1] = readValue(jr, "description");
209             tableProperties[2] = readValue(jr, "class");
210             Throw.when(!tableProperties[2].endsWith("ListDataTable"), IOException.class,
211                     "Currently, this method can only recreate a ListDataTable");
212 
213             // column metadata
214             List<DataColumn<?>> columns = new ArrayList<>();
215             int index = 0;
216             readName(jr, "columns");
217             jr.beginArray();
218             while (jr.peek().equals(JsonToken.BEGIN_OBJECT))
219             {
220                 String[] columnProperties = new String[4];
221                 jr.beginObject();
222                 columnProperties[0] = readValue(jr, "nr");
223                 columnProperties[1] = readValue(jr, "id");
224                 columnProperties[2] = readValue(jr, "description");
225                 columnProperties[3] = readValue(jr, "type");
226                 jr.endObject();
227 
228                 if (Integer.valueOf(columnProperties[0]).intValue() != index)
229                 {
230                     throw new IOException("column nr not ok");
231                 }
232                 String type = columnProperties[3];
233                 Class<?> valueClass = Primitive.forName(type);
234                 if (valueClass == null)
235                 {
236                     try
237                     {
238                         valueClass = Class.forName(type);
239                     }
240                     catch (ClassNotFoundException exception)
241                     {
242                         throw new IOException("Could not find class " + type, exception);
243                     }
244                 }
245                 @SuppressWarnings({ "rawtypes", "unchecked" })
246                 DataColumn<?> column = new SimpleDataColumn(columnProperties[1], columnProperties[2], valueClass);
247                 columns.add(column);
248                 index++;
249             }
250             jr.endArray(); // columns
251             jr.endObject(); // table
252 
253             ListDataTablestDataTable">ListDataTable dataTable = new ListDataTable(tableProperties[0], tableProperties[1], columns);
254 
255             // obtain the serializers
256             TextSerializer<?>[] serializers = new TextSerializer[dataTable.getNumberOfColumns()];
257             for (int i = 0; i < dataTable.getNumberOfColumns(); i++)
258             {
259                 DataColumn<?> column = dataTable.getColumns().get(i);
260                 serializers[i] = TextSerializer.resolve(column.getValueType());
261             }
262 
263             // read the data file records
264             readName(jr, "data");
265             jr.beginArray();
266             while (jr.peek().equals(JsonToken.BEGIN_ARRAY))
267             {
268                 Object[] values = new Object[columns.size()];
269                 jr.beginArray();
270                 for (int i = 0; i < dataTable.getNumberOfColumns(); i++)
271                 {
272                     jr.beginObject();
273                     values[i] = serializers[i].deserialize(readValue(jr, "" + i));
274                     jr.endObject();
275                 }
276                 jr.endArray(); // record
277                 dataTable.addRecord(values);
278             }
279 
280             // end JSON document
281             jr.endArray(); // data array
282             jr.endObject(); // data
283             return dataTable;
284         }
285         finally
286         {
287             if (null != jr)
288             {
289                 jr.close();
290             }
291         }
292     }
293 
294     /**
295      * Read a name - value pair from the JSON file where name has to match the given tag name.
296      * @param jr the JSON stream reader
297      * @param tag the tag to retrieve
298      * @return the value belonging to the tag
299      * @throws IllegalFormatException when the next element in the file did not contain the right tag
300      * @throws IOException when reading from the stream raises an exception
301      */
302     private static String readValue(final JsonReader jr, final String tag) throws IllegalFormatException, IOException
303     {
304         Throw.when(!jr.nextName().equals(tag), IllegalFormatException.class, "readValue: no %s object", tag);
305         return jr.nextString();
306     }
307 
308     /**
309      * Read a name -from the JSON file where name has to match the given tag name.
310      * @param jr the JSON stream reader
311      * @param tag the tag to retrieve
312      * @throws IllegalFormatException when the next element in the file did not contain the right tag
313      * @throws IOException when reading from the stream raises an exception
314      */
315     private static void readName(final JsonReader jr, final String tag) throws IllegalFormatException, IOException
316     {
317         Throw.when(!jr.nextName().equals(tag), IllegalFormatException.class, "readName: no %s object", tag);
318     }
319 
320     /**
321      * Read the data from the csv-file into the data table. Use the metadata to reconstruct the data table.
322      * @param filename String; the file name to read the data from
323      * @return dataTable the data table reconstructed from the meta data and filled with the data
324      * @throws IOException on I/O error when reading the data
325      * @throws TextSerializationException on unknown data type for serialization
326      */
327     public static DataTable readData(final String filename) throws IOException, TextSerializationException
328     {
329         FileReader fr = null;
330         try
331         {
332             fr = new FileReader(filename);
333             return readData(fr);
334         }
335         finally
336         {
337             if (null != fr)
338             {
339                 fr.close();
340             }
341         }
342     }
343     
344 }