Search in sources :

Example 1 with UriTypeAdapterFactory

use of org.terasology.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("Behaviors:fallback"), BehaviorTree.class).get());
            }
        });
        gson = gsonBuilder.create();
    }
}
Also used : AssetManager(org.terasology.assets.management.AssetManager) GsonBuilder(com.google.gson.GsonBuilder) UriTypeAdapterFactory(org.terasology.utilities.gson.UriTypeAdapterFactory) JsonReader(com.google.gson.stream.JsonReader) IOException(java.io.IOException) BehaviorTree(org.terasology.logic.behavior.asset.BehaviorTree) ResourceUrn(org.terasology.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 ResourceUrn (org.terasology.assets.ResourceUrn)1 AssetManager (org.terasology.assets.management.AssetManager)1 BehaviorTree (org.terasology.logic.behavior.asset.BehaviorTree)1 UriTypeAdapterFactory (org.terasology.utilities.gson.UriTypeAdapterFactory)1