Skip to content
Daniel Anderson edited this page May 23, 2019 · 16 revisions

Introduction

The module is the fallback serializer when you do not (want to) use LibGDX. For GWT/browser support use the libgdx-json module.

It has no extra benefit over the LibGDX serializer, and lacks serializers for libgdx classes.

Setup

  1. Include artemis-odb-serializer-json module in your gradle/maven configuration.
  2. Add the required manager and configure a backend:
     final WorldSerializationManager manager = new WorldSerializationManager();
     World world = new World(new WorldConfiguration().setSystem(manager));
     manager.setSerializer(new JsonArtemisSerializer(world))

Usage examples

Load from file

     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.

Save to string

      final ByteArrayOutputStream bos = new ByteArrayOutputStream();
      manager.save(bos, new SaveFileFormat(entities));
      String json = new String(bos.toByteArray());

entities is an IntBag with entity IDs defining the scope of the save operation.

Save to file

        Path path = Paths.get("level.json");
        FileOutputStream fos = new FileOutputStream(path.toFile(), false)
        manager.save(fos, new SaveFileFormat(entities));
        fos.flush();

Full Sample String and File

    public static void main(String[] args) throws IOException {
        // Setup the world and serializer
        final WorldSerializationManager manager = new WorldSerializationManager();
        final TagManager tagManager = new TagManager();

        World world = new World(new WorldConfiguration().setSystem(manager).setSystem(tagManager));
        manager.setSerializer(new JsonArtemisSerializer(world));

        // Create various simple and complex entities
        int simple1 = world.create();
        int simple2 = world.create();
        int simple3 = world.create();

        // Add some test tags
        tagManager.register("TestTag1", simple1);
        tagManager.register("TestTag2", simple2);
        tagManager.register("TestTag3", simple3);

        // Process once
        world.process();

        // Collect the entities
        EntitySubscription entitySubscription = world.getAspectSubscriptionManager().get(Aspect.all());
        IntBag entities = entitySubscription.getEntities();

        // Write to String
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        manager.save(bos, new SaveFileFormat(entities));
        String json = new String(bos.toByteArray());
        System.out.println(json);

        // Write to File
        Path path = Paths.get("level.json");
        FileOutputStream fos = new FileOutputStream(path.toFile(), false);
        manager.save(fos, new SaveFileFormat(entities));
        fos.flush();
    }
Clone this wiki locally