HTML and CSS Reference
In-Depth Information
Reading file content
To read the content of the selected file you use the
readTextAsync
method on the
Windows.Stor-
age.FileIO
object. The method returns the entire content of the file as a string of text. The
Windows.
Storage.FileIO
object, however, also provides two more methods. One is
readLinesAsync,
which reads
the entire content and returns it as an array of lines of text. Using
readLinesAsync
or
readTextAsync
depends on what you plan to do with the read text. For the purpose of deserializing some JSON
content, this method is the perfect fit since you are not going to split the text in lines anyway.
The other method available on the
Windows.Storage.FileIO
object is
readBufferAsync
. This method
returns a buffer object, namely an array of bytes. This might be a good fit if you are working with
binary files such as images. For text-based applications, you may safely ignore this method.
Here's the code to add to the
TodoList.invokeOpenPicker
method to grab the JSON string stored in
the selected file.
openPicker.pickSingleFileAsync().then(function (file) {
if (file) {
var io = Windows.Storage.FileIO;
io.readTextAsync(file)
.done(function (json) {
// JSON deserialization takes place here
}
});
The final step is deserializing the JSON string into a newly created
Task
object.
Deserializing
Task
objects
To serialize a
Task
object to a string you used the
JSON.stringify
method. A reverse method also exists
to revive a JSON string back to a JavaScript object. This method is
JSON.parse
. Here's the code you
need to add to the
TodoList.invokeOpenPicker
method:
// Build a Task object
var task = JSON.parse(json);
// Display the Task object
TodoList.displayTask(task);
Unfortunately, during execution this code raises an exception. The exception is due to a failure in
the building of the date of the
Task
object. As weird as it may sound, what
JSON.stringify
serializes, its
counterpart
JSON.parse
can't properly deserialize.
To be precise, this conflict shows up only if the serialized object has
Date
properties. If dates
are not involved, then everything goes smoothly. The problem can be tracked back to the JSON
specification that does not officially include the
Date
type. The major issue here is not that
JSON.parse
can't handle a date string. More subtly, the issue is that it deserializes it as a plain string. So you won't
Search WWH ::
Custom Search