-
Notifications
You must be signed in to change notification settings - Fork 75
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1f0117a
commit d18d78b
Showing
3 changed files
with
68 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
src/main/java/com/github/tartaricacid/touhoulittlemaid/util/NBTToJson.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package com.github.tartaricacid.touhoulittlemaid.util; | ||
|
||
import com.google.gson.JsonArray; | ||
import com.google.gson.JsonElement; | ||
import com.google.gson.JsonObject; | ||
import com.google.gson.JsonPrimitive; | ||
import net.minecraft.nbt.*; | ||
|
||
import javax.annotation.Nullable; | ||
import java.util.Optional; | ||
|
||
@SuppressWarnings("AlibabaClassNamingShouldBeCamel") | ||
public final class NBTToJson { | ||
public static Optional<JsonElement> getJson(@Nullable INBT nbt) { | ||
JsonElement element = null; | ||
if (nbt instanceof CollectionNBT) { | ||
element = collection((CollectionNBT<?>) nbt); | ||
} | ||
if (nbt instanceof CompoundNBT) { | ||
element = compound((CompoundNBT) nbt); | ||
} | ||
if (nbt instanceof StringNBT) { | ||
element = string((StringNBT) nbt); | ||
} | ||
if (nbt instanceof NumberNBT) { | ||
element = number((NumberNBT) nbt); | ||
} | ||
return Optional.ofNullable(element); | ||
} | ||
|
||
private static JsonElement collection(CollectionNBT<?> nbt) { | ||
JsonArray array = new JsonArray(); | ||
nbt.forEach(e -> getJson(e).ifPresent(array::add)); | ||
return array; | ||
} | ||
|
||
private static JsonElement compound(CompoundNBT nbt) { | ||
JsonObject object = new JsonObject(); | ||
nbt.getAllKeys().forEach(k -> getJson(nbt.get(k)).ifPresent(e -> object.add(k, e))); | ||
return object; | ||
} | ||
|
||
private static JsonElement string(StringNBT nbt) { | ||
return new JsonPrimitive(nbt.getAsString()); | ||
} | ||
|
||
private static JsonElement number(NumberNBT nbt) { | ||
return new JsonPrimitive(nbt.getAsNumber()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters