Skip to content

Instantly share code, notes, and snippets.

@SpaceManiac
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpaceManiac/627abce25a01e4f2215a to your computer and use it in GitHub Desktop.
Save SpaceManiac/627abce25a01e4f2215a to your computer and use it in GitHub Desktop.
Serialization/deserialization of entire inventories
// Usage:
inv.setContents(deserializeAll(config.getMapList("xyz")));
config.set("xyz", serializeAll(inv.getContents()));
// Methods:
private ArrayList<Map<String, Object>> serializeAll(ItemStack[] contents) {
ArrayList<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
if (contents == null) return items;
for (ItemStack item : contents) {
if (item == null) {
items.add(new HashMap<String, Object>());
} else {
items.add(item.serialize());
}
}
return items;
}
private ItemStack[] deserializeAll(List<Map<?, ?>> data) {
if (data == null) return new ItemStack[0];
ItemStack items[] = new ItemStack[data.size()];
for (int i = 0; i < data.size(); ++i) {
Map<String, Object> map = stringObject(data.get(i));
if (map.size() > 0) {
items[i] = ItemStack.deserialize(map);
}
}
return items;
}
private Map<String, Object> stringObject(Map<?, ?> map) {
Map<String, Object> result = new HashMap<String, Object>();
for (Map.Entry<?, ?> entry : map.entrySet()) {
result.put(entry.getKey().toString(), entry.getValue());
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment