Search in sources :

Example 1 with UriTypeAdapterFactory

use of org.terasology.engine.utilities.gson.UriTypeAdapterFactory in project Terasology by MovingBlocks.

the class BehaviorTreeBuilder method initGson.

private void initGson() {
    if (gson == null) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeHierarchyAdapter(BehaviorNode.class, this);
        gsonBuilder.registerTypeAdapterFactory(new UriTypeAdapterFactory());
        gsonBuilder.registerTypeAdapter(BehaviorTree.class, new TypeAdapter<BehaviorTree>() {

            @Override
            public void write(JsonWriter out, BehaviorTree value) throws IOException {
                if (value != null) {
                    // TODO doublecheck URN
                    out.value(value.getUrn().toString());
                } else {
                    out.value("");
                }
            }

            @Override
            public BehaviorTree read(JsonReader in) throws IOException {
                String uri = in.nextString();
                AssetManager assetManager = CoreRegistry.get(AssetManager.class);
                return assetManager.getAsset(new ResourceUrn(uri), BehaviorTree.class).orElse(assetManager.getAsset(new ResourceUrn("engine:default"), BehaviorTree.class).get());
            }
        });
        gson = gsonBuilder.create();
    }
}
Also used : AssetManager(org.terasology.gestalt.assets.management.AssetManager) GsonBuilder(com.google.gson.GsonBuilder) UriTypeAdapterFactory(org.terasology.engine.utilities.gson.UriTypeAdapterFactory) JsonReader(com.google.gson.stream.JsonReader) IOException(java.io.IOException) BehaviorTree(org.terasology.engine.logic.behavior.asset.BehaviorTree) ResourceUrn(org.terasology.gestalt.assets.ResourceUrn) JsonWriter(com.google.gson.stream.JsonWriter)

Aggregations

GsonBuilder (com.google.gson.GsonBuilder)1 JsonReader (com.google.gson.stream.JsonReader)1 JsonWriter (com.google.gson.stream.JsonWriter)1 IOException (java.io.IOException)1 BehaviorTree (org.terasology.engine.logic.behavior.asset.BehaviorTree)1 UriTypeAdapterFactory (org.terasology.engine.utilities.gson.UriTypeAdapterFactory)1 ResourceUrn (org.terasology.gestalt.assets.ResourceUrn)1 AssetManager (org.terasology.gestalt.assets.management.AssetManager)1