Be more smart about json-serializing items

Don't include nbt_hex if we don't have a NBT tag
Don't include damage unless it's non-zero
Don't include count unless it's non-1
This commit is contained in:
Dylan K. Taylor
2017-08-24 12:02:03 +01:00
parent 2443a57234
commit 17518195d1

View File

@ -859,12 +859,23 @@ class Item implements ItemIds, \JsonSerializable{
* @return array * @return array
*/ */
final public function jsonSerialize(){ final public function jsonSerialize(){
return [ $data = [
"id" => $this->getId(), "id" => $this->getId()
"damage" => $this->getDamage(),
"count" => $this->getCount(),
"nbt_hex" => bin2hex($this->getCompoundTag())
]; ];
if($this->getDamage() !== 0){
$data["damage"] = $this->getDamage();
}
if($this->getCount() !== 1){
$data["count"] = $this->getCount();
}
if($this->hasCompoundTag()){
$data["nbt_hex"] = bin2hex($this->getCompoundTag());
}
return $data;
} }
/** /**
@ -876,9 +887,9 @@ class Item implements ItemIds, \JsonSerializable{
final public static function jsonDeserialize(array $data) : Item{ final public static function jsonDeserialize(array $data) : Item{
return ItemFactory::get( return ItemFactory::get(
(int) $data["id"], (int) $data["id"],
(int) $data["damage"], (int) ($data["damage"] ?? 0),
(int) $data["count"], (int) ($data["count"] ?? 1),
(string) ($data["nbt"] ?? hex2bin($data["nbt_hex"])) //`nbt` key might contain old raw data (string) ($data["nbt"] ?? (isset($data["nbt_hex"]) ? hex2bin($data["nbt_hex"]) : "")) //`nbt` key might contain old raw data
); );
} }