-
Notifications
You must be signed in to change notification settings - Fork 114
libgdx json
The module is the recommended json serializer when using LibGDX or when you plan to target HTML5 now or in the future. Provides serialization for all odb platforms.
-
Add
artemis-odb-serializer-json-libgdx
module as dependency to your gradle/maven configuration. To your core module for LibGDX projects. -
To your Html module:
implementation "net.onedaybeard.artemis:artemis-odb-serializer:$artemisOdbVersion:sources"
implementation "net.onedaybeard.artemis:artemis-odb-serializer-json-libgdx:$artemisOdbVersion:sources"
-
To your GdxDefinition.gwt.xml:
<inherits name="com.artemis-json-libgdx" />
-
Add the required manager and configure the json backend:
final WorldSerializationManager manager = new WorldSerializationManager();
World world = new World(new WorldConfiguration().setSystem(manager));
manager.setSerializer(new JsonArtemisSerializer(world));
final InputStream is = AnyClass.class.getResourceAsStream("level.json");
manager.load(is, SaveFileFormat.class);
Anything already in the world is unaffected by the load, so you can incrementally load parts of a world.
final PrintWriter writer = new PrintWriter("level.json", "UTF-8");
manager.save(writer, new SaveFileFormat(entities));
writer.close();
final StringWriter writer = new StringWriter();
manager.save(writer, new SaveFileFormat(entities));
String json = writer.toString();
entities
is an IntBag with entity IDs defining the scope of the save operation.
Full example:
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();
}
final EntitySubscription allEntities = world.getManager(AspectSubscriptionManager.class).get(Aspect.all());
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final SaveFileFormat save = new SaveFileFormat(allEntities.getEntities());
world.getSystem(WorldSerializationManager.class).save(baos , save);
final Preferences preferences = Gdx.app.getPreferences("MyGame");
preferences.putString("MyStateId", baos.toString("UTF-8"));
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
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);
}
- Overview
- Concepts
- Getting Started
- Using
- More guides
- Plugins
- Game Gallery
- Tools and Frameworks
- API reference