1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19: 20:
21: final class NJson
22: {
23: const FORCE_ARRAY = 1;
24:
25:
26: private static $messages = array(
27: JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
28: JSON_ERROR_STATE_MISMATCH => 'Syntax error, malformed JSON',
29: JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
30: JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
31: );
32:
33:
34:
35: 36: 37:
38: final public function __construct()
39: {
40: throw new NStaticClassException;
41: }
42:
43:
44:
45: 46: 47: 48: 49:
50: public static function encode($value)
51: {
52: NDebugger::tryError();
53: if (function_exists('ini_set')) {
54: $old = ini_set('display_errors', 0);
55: $json = json_encode($value);
56: ini_set('display_errors', $old);
57: } else {
58: $json = json_encode($value);
59: }
60: if (NDebugger::catchError($e)) {
61: throw new NJsonException($e->getMessage());
62: }
63: return $json;
64: }
65:
66:
67:
68: 69: 70: 71: 72: 73:
74: public static function decode($json, $options = 0)
75: {
76: $json = (string) $json;
77: $value = json_decode($json, (bool) ($options & self::FORCE_ARRAY));
78: if ($value === NULL && $json !== '' && strcasecmp($json, 'null')) {
79: $error = PHP_VERSION_ID >= 50300 ? json_last_error() : 0;
80: throw new NJsonException(isset(self::$messages[$error]) ? self::$messages[$error] : 'Unknown error', $error);
81: }
82: return $value;
83: }
84:
85: }
86:
87:
88:
89: 90: 91: 92:
93: class NJsonException extends Exception
94: {
95: }
96: