top of page

Saving Java Objects As JSON and reading them back

11 minutes ago
4 min read

As a newbie to simulation modeling, I've often wondered whether I can save Java classes and load them again. For example, can you save scenarios and results to ensure reproducible, shareable results between users?


My mentor, Jaco-ben Vosloo, introduced me to the Jackson library for serializing Java objects to JSON files and deserializing them.

Converting Java objects to JSON files
Converting Java objects to JSON files



What is serialization?

Serialization and Deserialization are important Java mechanisms used to convert objects into a byte stream and reconstruct them back into objects. Together, they enable object persistence, data transfer, and communication between different systems while preserving an object's state.

  • Serialization converts an object into a byte stream for storage or transmission.

  • Deserialization converts the byte stream back into the original Java object.

Source: https://www.geeksforgeeks.org/java/serialization-and-deserialization-in-java/

Now you also know why you get these parts in new Java classes you create in Anyogic. They allow AnyLogic to be able to save a snapshot of your model (in some file format) to the disk and load them again later.

Ever wondered why you see serializable in new Java classes?
Ever wondered why you see serializable in new Java classes?

See the YouTube short where he demonstrates this functionality here.


Now, let's get started.

Situation


We have a "MyDataClass" class consisting of two variables, a default constructor and a toString function. Note that the toString function prints both variables.


Our example data class with some default data for all fields
Our example data class with some default data for all fields

In main, we have a 'dataObject' variable which stores an instance of the 'MyDataClass' class, a button that assigns a value to the 'result' variable of the instance of said class and a text object that displays the toString function's output.


The model setup that creates a new data class object and saves it to a variable
The model setup that creates a new data class object and saves it to a variable


The challenge

We want to serialize the class instance to JSON and deserialize it in reverse. Essentially, load and download instances. How do you go about this?



The Solution

To add this functionality, we create our own the JSONHandler class. To create this class, you must import a few essential libraries (all of which is included in standard AnyLogic). The following table lists the imports and their functionality:


Import

Functionality

com.fasterxml.jackson.databind.ObjectMapper

Mapping the Java object's properties to JSON data(Serialisation) and vice versa(Deserialisation)

java.io.File

Provides an abstract representation of file and directory pathnames

java.io.IOException

Handles exceptions related to input or output files in the event of a file being absent or restrictive access permissions


The class has the following structure with the imports included:

(Model source is available at the end of the post, so no need to copy image and give it to AI to get the text and copy and paste it to your own AnyLogic model 😉)


The JSON Helper class that will load and save Java objects for us
The JSON Helper class that will load and save Java objects for us

The exportToJSON function passes the object and leverages the 'writeValue' function in the instance of the object mapper to create the file, and the exceptions are handled accordingly. The importFromJSON function leverages the 'readValue' function with a generic as a return type. This allows one to import files belonging to different classes easily.


Now, to leverage the configured class, loading and downloading objects must be added and configured as follows:


  1. For saving:

A "Save Data to JSON" button is added with the action of calling the export function from handler class, along with a File chooser object set to download and file name and format specified. This enables the saving and downloading of the file.


Button and code for saving a Java object
Button and code for saving a Java object

  1. Reading data from the already saved file: To use the saved file, we can call the import function and pass the file name and class. The imported object is stored in the 'loadedDataObject' variable of type MyDataClass.


    Button and code for loading a JSON object
    Button and code for loading a JSON object

  2. Reading data from an Uploaded a different file:

    You can also upload a different file using a button that calls the import function and uses a file chooser set to upload a defined file type. The imported object is stored in the 'customFileloadedDataObject' variable of type MyDataClass.


    Button, file chooser and code for loading a different JSON object
    Button, file chooser and code for loading a different JSON object

    The 'Read Data From Uploaded JSON' button is disabled if the file chooser doesn't have a file uploaded to avoid a null error. If a JSON file is uploaded, then the import function passes the file string name from the file chooser's value.


With the functionality successfully configured. We can observe it in action below:


All the steps in action! Creating, Saving and Loading
All the steps in action! Creating, Saving and Loading

You can download the example model below and test the functionality.





Selaelo Kgoale is a simulation enthusiast and junior engineer at The AnyLogic Modeler. To contact him, use LinkedIn.


What next?

If you liked this post, you could read more posts by following the links above. Why not subscribe to our blog or follow us on any of the social media accounts for future updates? The links are in the Menu bar at the top, or the footer at the bottom. You can also join the mobile app here!


If you really want to make a difference in supporting us please consider joining our Patreon community here 


If you want to contact us for some advice, maybe a potential partnership or project or just to say "Hi!", feel free to get in touch here, and we will get back to you soon!



Comments


  • LinkedIn
  • Facebook
  • YouTube
  • Twitter
  • Instagram

©2021 by The AnyLogic Modeler

bottom of page