I'm trying to JSON encode some objects in PHP, but I'm facing a problem: I want to encode data which is kept by a class private members. I found this piece of code to encode this object by calling an encode function like:
public function encodeJSON() { foreach ($this as $key => $value) { $json->$key = $value; } return json_encode($json); }
However, this only works if the object I want to encode does not contain other objects inside, which is the case. How can I do to encode not only the "outer" object, but encode as well any members that are objects too?
The json_encode() function is used to encode a value to JSON format.
I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.
The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.
To encode objects into a JSON formatted string in PHP, you can use the json_encode(value, options, depth) function. The first parameter specifies the PHP object to encode. You can control how the PHP object will be encoded into JSON by passing a combination of bitmasks in the second parameter.
The best method to serialize an object with private properties is to implement the \JsonSerializable interface and then implement your own JsonSerialize method to return the data you require to be serialized.
<?php class Item implements \JsonSerializable { private $var; private $var1; private $var2; public function __construct() { // ... } public function jsonSerialize() { $vars = get_object_vars($this); return $vars; } }
json_encode
will now serialize your object correctly.
If you're using php 5.4 you can use the JsonSerializable interface: http://www.php.net/manual/en/class.jsonserializable.php
You just implement a jsonSerialize method in your class which returns whatever you want to be encoded.
Then when you pass your object into json_encode, it'll encode the result of jsonSerialize.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With