I am developing a web application in PHP,
I need to transfer many objects from server as JSON string, is there any library existing for PHP to convert object to JSON and JSON String to Objec, like Gson library for Java.
We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.
Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google. The following points highlight why you should be using this library − Standardized − Gson is a standardized library that is managed by Google.
Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.
What is JSON? JSON stands for JavaScript Object Notation, and is a syntax for storing and exchanging data. Since the JSON format is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.
This should do the trick!
// convert object => json $json = json_encode($myObject); // convert json => object $obj = json_decode($json);
Here's an example
$foo = new StdClass(); $foo->hello = "world"; $foo->bar = "baz"; $json = json_encode($foo); echo $json; //=> {"hello":"world","bar":"baz"} print_r(json_decode($json)); // stdClass Object // ( // [hello] => world // [bar] => baz // )
If you want the output as an Array instead of an Object, pass true
to json_decode
print_r(json_decode($json, true)); // Array // ( // [hello] => world // [bar] => baz // )
More about json_encode()
See also: json_decode()
for more extendability for large scale apps use oop style with encapsulated fields.
Simple way :-
class Fruit implements JsonSerializable { private $type = 'Apple', $lastEaten = null; public function __construct() { $this->lastEaten = new DateTime(); } public function jsonSerialize() { return [ 'category' => $this->type, 'EatenTime' => $this->lastEaten->format(DateTime::ISO8601) ]; } }
echo json_encode(new Fruit()); //which outputs:
{"category":"Apple","EatenTime":"2013-01-31T11:17:07-0500"}
Real Gson on PHP :-
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