Skip to content

Commit

Permalink
fix passthrough because DFU encodes null values to json but doesn't d…
Browse files Browse the repository at this point in the history
…ecode properly

see: Mojang/DataFixerUpper#62
  • Loading branch information
Epic428 committed Jan 25, 2023
1 parent 5789b43 commit 07acf58
Showing 1 changed file with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.teamresourceful.resourcefullib.common.codecs;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import com.mojang.serialization.DataResult;
Expand Down Expand Up @@ -54,7 +56,7 @@ public static <T> Codec<T> passthrough(Function<T, JsonElement> encoder, Functio
return DataResult.success(decoder.apply(jsonElement));
}
return DataResult.error("Value was not an instance of JsonElement");
}, input -> new Dynamic<>(JsonOps.INSTANCE, encoder.apply(input)));
}, input -> new Dynamic<>(JsonOps.INSTANCE, clearNulls(encoder.apply(input))));
}

public static <S> Codec<S> eitherRight(Codec<Either<S, S>> eitherCodec) {
Expand All @@ -64,4 +66,26 @@ public static <S> Codec<S> eitherRight(Codec<Either<S, S>> eitherCodec) {
public static <S> Codec<S> eitherLeft(Codec<Either<S, S>> eitherCodec) {
return eitherCodec.xmap(e -> e.map(p -> p, p -> p), Either::left);
}

private static JsonElement clearNulls(JsonElement json) {
if (json instanceof JsonObject object) {
JsonObject newObject = new JsonObject();
for (String key : object.keySet()) {
JsonElement element = clearNulls(object.get(key));
if (element != null) {
newObject.add(key, element);
}
}
} else if (json instanceof JsonArray array) {
JsonArray newArray = new JsonArray();
for (JsonElement item : array) {
JsonElement element = clearNulls(item);
if (element != null) {
newArray.add(element);
}
}
return newArray;
}
return json.isJsonNull() ? null : json;
}
}

0 comments on commit 07acf58

Please sign in to comment.