Json.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. /*
  3. * To change this license header, choose License Headers in Project Properties.
  4. * To change this template file, choose Tools | Templates
  5. * and open the template in the editor.
  6. */
  7. /**
  8. * Description of Json
  9. *
  10. * @author jgao
  11. */
  12. class Json {
  13. //put your code here
  14. public static function encode($obj) {
  15. $json = json_encode($obj);
  16. if ($GLOBALS['OS'] == "linux") { # 还原中文字符串
  17. return preg_replace_callback('#\\\u([0-9a-f]{4})#i', function ($matches) {
  18. return iconv('UCS-2LE', 'UTF-8', pack('H4', $matches[1]));
  19. }, $json);
  20. } else if ($GLOBALS['OS'] == "win32") { # 还原中文字符串
  21. return preg_replace_callback('#\\\u([0-9a-f]{4})#i', function ($matches) {
  22. return iconv('UCS-2BE', 'UTF-8', pack('H4', $matches[1]));
  23. }, $json);
  24. }
  25. }
  26. public static function decode($data) {
  27. // 检测是否为json数据,如果不是则尝试解压缩
  28. $obj = json_decode($data);
  29. if (is_null($obj)) {
  30. $str = gzip_decode($data);
  31. $obj = json_decode($str);
  32. }
  33. return $obj;
  34. }
  35. }