Skip to content
Daan van Yperen edited this page Sep 24, 2016 · 42 revisions

artemis-odb-serializer-json-libgdx

Provides serialization for all platforms.

When?

The module is the recommended serializer when using LibGDX or when you plan to target HTMl5 now or in the future.

Basic Setup

For Gradle LibGDX projects, add the following to your core module.

compile "net.onedaybeard.artemis:artemis-odb-serializer-json-libgdx:2.0.0"

To enable GWT support read the GWT instructions

Register the Serializer

WorldSerializationManager worldSerializationManager = new WorldSerializationManager();

WorldConfiguration worldConfig = new WorldConfigurationBuilder()
    .with(
        worldSerializationManager
        // ...your other systems/managers
    ).build();

    world = new World(worldConfig);

    // Set serializer
    worldSerializationManager.setSerializer(new JsonArtemisSerializer(world));

To Json String

private String subscriptionToJson(EntitySubscription subscription) {
	final StringWriter writer = new StringWriter();
	final SaveFileFormat save = new SaveFileFormat(subscription.getEntities());
	world.getSystem(WorldSerializationManager.class).save(writer, save);
	return writer.toString();
}

Save to Local Storage

final EntitySubscription allEntities = world.getManager(AspectSubscriptionManager.class).get(Aspect.all());

try {
	final StringWriter writer = new StringWriter();
	final SaveFileFormat save = new SaveFileFormat(allEntities.getEntities());
	world.getSystem(WorldSerializationManager.class).save(writer, save);

	final Preferences preferences = Gdx.app.getPreferences("MyGame");
	preferences.putString("MyStateId", writer.toString());
	preferences.flush();
} catch (Exception e) {
	Gdx.app.error("MyGame", "Save Failed", e);
}  

Local storage has a quota in most browsers! Article about local storage quota

Load from Local Storage

try {
	final Preferences preferences = Gdx.app.getPreferences("MyGame")
	final String json = preferences.getString("MyStateId");
	final ByteArrayInputStream is = new ByteArrayInputStream(json.getBytes("UTF-8"));
	world.getSystem(WorldSerializationManager.class).load(is,SaveFileFormat.class);
} catch (Exception e) {
	Gdx.app.error("MyGame", "Load Failed", e);
}
Clone this wiki locally