Created
July 24, 2015 00:29
-
-
Save aikar/131b372f9f47c2e3834d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* 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