Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
JsonSerializer.php
Go to the documentation of this file.
1 <?php
7 
12 {
16  private $jsonErrorMessages = [
17  JSON_ERROR_DEPTH => 'Maximum depth exceeded',
18  JSON_ERROR_STATE_MISMATCH => 'State mismatch',
19  JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
20  JSON_ERROR_SYNTAX => 'Syntax error, invalid JSON',
21  ];
22 
30  public function jsonEncode($data)
31  {
32  $ret = json_encode($data);
33  $this->checkJsonError($data);
34 
35  // return the json String
36  return $ret;
37  }
38 
47  public function jsonDecode($data, $asArray = true)
48  {
49  $ret = json_decode($data, $asArray);
50  $this->checkJsonError($data);
51 
52  // return the array
53  return $ret;
54  }
55 
61  private function checkJsonError()
62  {
63  $jsonError = json_last_error();
64  if ($jsonError !== JSON_ERROR_NONE) {
65  // find appropriate error message
66  $message = 'Unknown JSON Error';
67  if (isset($this->jsonErrorMessages[$jsonError])) {
68  $message = $this->jsonErrorMessages[$jsonError];
69  }
70 
71  throw new \Exception(
72  'JSON Encoding / Decoding error: ' . $message . var_export(func_get_arg(0), true),
73  $jsonError
74  );
75  }
76  }
77 }
$message