Created
September 6, 2013 13:38
-
-
Save ircmaxell/6463913 to your computer and use it in GitHub Desktop.
JSON utility class
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
<?php | |
require 'json.php'; | |
$json = new JSON; | |
$json->foo->bar->baz = "foo"; | |
$json->foo->biz = "test"; | |
$json->baz = array(); | |
$json->baz[1] = "testing"; | |
$json->baz[2] = "this"; | |
$json->baz[3] = "out!"; | |
$j2 = JSON::fromJSON($json->toJSON()); | |
var_dump($json, $j2); |
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
<?php | |
class JSON implements JSONSerializable { | |
protected $data = array(); | |
public function &__get($key) { | |
if (!isset($this->data[$key])) { | |
$this->data[$key] = new static; | |
} | |
return $this->data[$key]; | |
} | |
public function __set($key, $value) { | |
$this->data[$key] = $value; | |
} | |
public function __isset($key) { | |
return isset($this->data[$key]); | |
} | |
public function __unset($key) { | |
unset($this->data[$key]); | |
} | |
public function jsonSerialize() { | |
return $this->data; | |
} | |
public function toJSON() { | |
return json_encode($this); | |
} | |
public static function fromJSON($json) { | |
$tmp = json_decode($json); | |
return self::parseJSONResult($tmp); | |
} | |
private static function parseJSONResult($json) { | |
if (is_object($json)) { | |
$obj = new static; | |
foreach (get_object_vars($json) as $key => $value) { | |
$obj->$key = self::parseJSONResult($value); | |
} | |
return $obj; | |
} elseif (is_array($json)) { | |
$ret = array(); | |
foreach ($json as $key => $value) { | |
$ret[$key] = self::parseJSONResult($value); | |
} | |
return $ret; | |
} | |
return $json; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment