'how cann I convert php class to json [closed]
I am trying to convert a simple class object to json as string. It does not work!. could you help me please.
here are my files:
Peson.php
<?php
class Person
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function toJson()
{
return json_encode($this);
}
}
?>
index.php
include 'Person.php';
$person = new Person();
$person->setName("John");
echo $person->toJson();
Result :
Solution 1:[1]
You're getting an empty object because your class doesn't have any public properties to encode. Change name from private to public and you'll get output like this: {"name":"John"}
Solution 2:[2]
You can use get_object_vars for this.
public function toJson()
{
return json_encode(get_object_vars($this)); //returns {"name":"stringNameHere"}
}
More info about get_object_vars here.
This is how your code would look:
class Person
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function toJson()
{
return json_encode(get_object_vars($this));
}
}
$person = new Person();
$person->setName('testName');
echo $person->toJson(); //Print {"name":"testName"}
Here you have a live code example
Solution 3:[3]
In this case you get an empty object because the properties are private. A way to keep your properties private and still geting their values in a JSON is using the JsonSerializable Interface. Then implementing its method jsonSerialize().
class Person implements JsonSerializable
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function jsonSerialize()
{
$vars = get_object_vars($this);
return $vars;
}
}
Solution 4:[4]
<?php
class Person implements \JsonSerializable
{
private $name;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function jsonSerialize()
{
return get_object_vars($this);
}
}
?>
then, you can convert your person object to JSON with json_encode
$person = new Person();
$person->setName("John");
echo json_encode($person);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | outlaw |
| Solution 2 | Voxxii |
| Solution 3 | Csharls |
| Solution 4 | Who Do You think am i |
