Skip to content

Instantly share code, notes, and snippets.

@aikar
Created July 24, 2015 00:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aikar/131b372f9f47c2e3834d to your computer and use it in GitHub Desktop.
Save aikar/131b372f9f47c2e3834d to your computer and use it in GitHub Desktop.
/*
* Copyright (c) 2015. Starlis LLC / dba Empire Minecraft
*
* This source code is proprietary software and must not be redistributed without Starlis LLC's approval
*
*/
package com.empireminecraft.util.serialization;
import com.empireminecraft.util.Util;
import com.empireminecraft.util.json.JsonConfiguration;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
public class Serialization {
public static void initialize() {
}
public static String serializeInventory(Inventory inventory) {
JsonConfiguration json = new JsonConfiguration();
json.set("size", inventory.getSize());
json.set("name", inventory.getTitle());
int idx = 0;
HashMap<String, ItemStack> items = new HashMap<>();
for (ItemStack item : inventory.getContents()) {
int i = idx++;
if (item == null) {
continue;
}
items.put("" + i, item);
}
json.createSection("items", items);
return json.saveToString();
}
public static String dumpItem(ItemStack itemStack) {
JsonConfiguration json = new JsonConfiguration();
json.set("item", itemStack);
return json.saveToString();
}
public static Inventory serializeInventory(String jsons) throws InvalidConfigurationException {
return deserializeInventory(jsons, null);
}
public static Inventory deserializeInventory(String jsons, String title) throws InvalidConfigurationException {
try {
JsonConfiguration json = new JsonConfiguration();
json.loadFromString(jsons);
int size = json.getInt("size", 54);
if (title == null) {
title = json.getString("name");
}
Inventory inventory = Bukkit.createInventory(null, size, title);
Map<String, Object> items = json.getConfigurationSection("items").getValues(false);
for (Map.Entry<String, Object> item : items.entrySet()) {
ItemStack itemstack = (ItemStack) item.getValue();
int idx = Integer.parseInt(item.getKey());
inventory.setItem(idx, itemstack);
}
return inventory;
} catch (InvalidConfigurationException e) {
Util.printException("Exception in deserializeYaml" + jsons, e);
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment