JSON Serialization

In some cases, a JavaScript developer may need to serialize an instance of a JavaScript class into a string, and restore it later. For example, the script might want to store the preferred APN to a text file on the file system, so that another script can restore it later, after the APN profile has been revoked.

Serialization

In order to store an instance of a class to a file, it first needs to be converted into a JSON string using JSON.stringify. The following code snippet shows how to serialize the preferred APN into a text file:

var preferredApn = mobicontrol.apn.getPreferred();
var jsonString = JSON.stringify(preferredApn);
var jsonFile = new mobicontrol.io.File(mobicontrol.storage.internal.dataDirectory + '/preferredApn.json');
jsonFile.writeText(jsonString);

Deserialization

In order to restore an instance of a class from a JSON string, one must use JSON.parse, providing mobicontrol.json.revive function as the second parameter. If this parameter is not provided, such objects will not be properly restored and will become native JavaScript objects instead. The following code snippet shows how to deserialize a stored APN, install it, and set it as the preferred APN:

var jsonFile = new mobicontrol.io.File(mobicontrol.storage.internal.dataDirectory + '/preferredApn.json');
var jsonString = jsonFile.readText();
var apnConfig = JSON.parse(jsonString, mobicontrol.json.revive);
var installedApn = mobicontrol.apn.install(apnConfig);
mobicontrol.apn.setPreferred(installedApn);

Serializing Complex Data

The same technique can be used to serialize and deserialize complex data, for example arrays of class instances, or nested classes. The code snippet below shows how to store all installed APNs and the preferred APN for the current operator. Note the construction of a new native JavaScript object with two fields, one of which is an array of APN instances:

var allConfig = {
    installedApns: mobicontrol.apn.listCurrentOperatorApns(),
    preferredApn: mobicontrol.apn.getPreferred().apn
};
var jsonFile = new mobicontrol.io.File(mobicontrol.storage.internal.dataDirectory + '/allApnConfig.json');
jsonFile.writeText(JSON.stringify(allConfig));

And here is how we can restore this complex APN configuration:

var jsonFile = new mobicontrol.io.File(mobicontrol.storage.internal.dataDirectory + '/allApnConfig.json');
var allConfig = JSON.parse(jsonFile.readText(), mobicontrol.json.revive);
allConfig.installedApns.forEach(
    config => {
        var apn = mobicontrol.apn.install(config);
        if (apn.apn == allConfig.preferredApn) {
            mobicontrol.apn.setPreferred(apn);
        }
    });

Revivable Classes

The Apn class is said to be revivable, which means its instances can be serialized into a JSON string and successfully restored later. Revivable classes have a toJSON function (e.g. Apn.toJSON) and are documented accordingly. Not all classes are revivable.