Skip to content

Commit

Permalink
Add a method to GenericDataProvider to save JSON using a codec
Browse files Browse the repository at this point in the history
Seems like the type of thing that is going to start coming up frequently
  • Loading branch information
KnightMiner committed Mar 16, 2024
1 parent 14479ee commit 9922b9e
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/main/java/slimeknights/mantle/data/GenericDataProvider.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
package slimeknights.mantle.data;

import com.google.gson.Gson;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataGenerator;
import net.minecraft.data.DataProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import slimeknights.mantle.Mantle;
import slimeknights.mantle.util.JsonHelper;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/** Generic logic to convert any serializable object into JSON. */
@SuppressWarnings("unused") // API
@RequiredArgsConstructor
@Log4j2
public abstract class GenericDataProvider implements DataProvider {
Expand All @@ -41,4 +45,15 @@ protected void saveJson(CachedOutput output, ResourceLocation location, Object o
log.error("Couldn't create data for {}", location, e);
}
}

/**
* Saves the given object to JSON using a codec
* @param output Output for writing
* @param location Location relative to this data provider's root
* @param codec Codec to save the object
* @param object Object to save, will be converted using the passed codec
*/
protected <T> void saveJson(CachedOutput output, ResourceLocation location, Codec<T> codec, T object) {
saveJson(output, location, codec.encodeStart(JsonOps.INSTANCE, object).getOrThrow(false, Mantle.logger::error));
}
}

0 comments on commit 9922b9e

Please sign in to comment.