4.8.17. Export and Import Entities in JSON

The platform provides an API for exporting and importing graphs of entities in JSON format. It is available on Middleware via the EntityImportExportAPI interface and on the client tier via EntityImportExportService. These interfaces have an identical set of methods which are described below. The export/import implementation delegates to the EntitySerializationAPI interface which can also be used directly.

  • exportEntitiesToJSON() - serializes a collection of entities to JSON.

    @Inject
    private EntityImportExportService entityImportExportService;
    @Inject
    private GroupDatasource<Customer, UUID> customersDs;
    
    ...
    String jsonFromDs = entityImportExportService.exportEntitiesToJSON(customersDs.getItems());
  • exportEntitiesToZIP() - serializes a collection of entities to JSON and packs the JSON file into ZIP archive. In the following example, the ZIP archive is saved to the file storage using the FileLoader interface:

    @Inject
    private EntityImportExportService entityImportExportService;
    @Inject
    private GroupDatasource<Customer, UUID> customersDs;
    @Inject
    private Metadata metadata;
    @Inject
    private DataManager dataManager;
    
    ...
    byte[] array = entityImportExportService.exportEntitiesToZIP(customersDs.getItems());
    FileDescriptor descriptor = metadata.create(FileDescriptor.class);
    descriptor.setName("customersDs.zip");
    descriptor.setExtension("zip");
    descriptor.setSize((long) array.length);
    descriptor.setCreateDate(new Date());
    try {
        fileLoader.saveStream(descriptor, () -> new ByteArrayInputStream(array));
    } catch (FileStorageException e) {
        throw new RuntimeException(e);
    }
    dataManager.commit(descriptor);
  • importEntitiesFromJSON() - deserializes the JSON and persists deserialized entities according to the rules, described by the entityImportView parameter (see JavaDocs on the EntityImportView class). If an entity is not present in the database, it will be created. Otherwise the fields of the existing entity that are specified in the entityImportView will be updated.

  • importEntitiesFromZIP() - reads a ZIP archive that contains a JSON file, deserializes the JSON and persists deserialized entities like the importEntitiesFromJSON() method.

    @Inject
    private EntityImportExportService entityImportExportService;
    @Inject
    private FileLoader fileLoader;
    
    private FileDescriptor descriptor;
    
    ...
    EntityImportView view = new EntityImportView(Customer.class);
    view.addLocalProperties();
    try {
        byte[] array = IOUtils.toByteArray(fileLoader.openStream(descriptor));
        Collection<Entity> collection = entityImportExportService.importEntitiesFromZIP(array, view);
    } catch (FileStorageException e) {
        throw new RuntimeException(e);
    }