> For the complete documentation index, see [llms.txt](https://learnphp.gitbook.io/learnphp/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learnphp.gitbook.io/learnphp/advanced/using-jsonserializable-in-an-object-ok.md).

# Using JsonSerializable in an Object (ok)

Đã thực hành:<br>

![](/files/-MgySl4avaOA5oShe0SQ)

C:\xampp\htdocs\php\model.php

```
<?php  
	class Model {
	  public function __construct() {}
	}
?>
```

C:\xampp\htdocs\php\index.php

```
<?php  
include_once "model.php";
class User extends Model implements JsonSerializable {
    public $id;
    public $name;
    public $surname;
    public $username;
    public $password;
    public $email;
    public $date_created;
    public $date_edit;
    public $role;
    public $status;
    public function __construct(){
      $this->name = "Lionel";
      $this->surname = "Pham";
      $this->username = $this->name . " " . $this->surname;
    }
    public function jsonSerialize() {
        return [
            'name' => $this->name,
            'surname' => $this->surname,
            'username' => $this->username
        ];
    }
}
$User = new User();
echo '<pre>';
  echo json_encode($User);
echo '</pre>';
?>
```

\========== :) ===========

When you build REST API's, you may need to reduce the information of an object to be passed to the client application. For this purpose, this example illustrates how to use the `JsonSerialiazble` interface.

In this example, the class `User` actually extends a DB model object of a hypotetical ORM.

```
class User extends Model implements JsonSerializable {
    public $id;
    public $name;
    public $surname;
    public $username;
    public $password;
    public $email;
    public $date_created;
    public $date_edit;
    public $role;
    public $status;

    public function jsonSerialize() {
        return [
            'name' => $this->name,
            'surname' => $this->surname,
            'username' => $this->username
        ];
    }
}
```

Add `JsonSerializable` implementation to the class, by providing the `jsonSerialize()` method.

```
public function jsonSerialize()
```

Now in your application controller or script, when passing the object User to `json_encode()` you will get the return json encoded array of the `jsonSerialize()` method instead of the entire object.

```
json_encode($User);
```

Will return:

```
{"name":"John", "surname":"Doe", "username" : "TestJson"}
```

#### properties values example.[#](https://riptutorial.com/php/example/7722/using-jsonserializable-in-an-object#undefined)

This will both reduce the amount of data returned from a RESTful endpoint, and allow to exclude object properties from a json representation.

### **Using Private and Protected Properties with `json_encode()`**[#](https://riptutorial.com/php/example/7722/using-jsonserializable-in-an-object#undefined)

To avoid using JsonSerializable, it is also possible to use private or protected properties to hide class information from `json_encode()` output. The Class then does not need to implement \JsonSerializable.

> The json\_encode() function will only encode public properties of a class into JSON.

```
<?php

class User {
    // private properties only within this class
    private $id;
    private $date_created;
    private $date_edit;

    // properties used in extended classes
    protected $password;
    protected $email;
    protected $role;
    protected $status;

    // share these properties with the end user        
    public $name;
    public $surname;
    public $username;

    // jsonSerialize() not needed here
}        

$theUser = new User();

var_dump(json_encode($theUser));
```

### **Output:**[#](https://riptutorial.com/php/example/7722/using-jsonserializable-in-an-object#undefined)

```
string(44) "{"name":null,"surname":null,"username":null}"
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/advanced/using-jsonserializable-in-an-object-ok.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
